In this post, I am going to discuss about the casting of object form one type to another type and what the Things required to be kept in mind when casting object. Casting basically takes place when we are relating between classes I.e. INHERITANCE. Classes have A parent child relationship, I.e. Is-a relationship between them. To understand it, take an example of the Below diagram: As show in the above image, Employee and Manager are having is-a relationship with person, I.e., inherited from person class.Now I have one method in my main class which takes Employee as argument and does processing on the property of the class.Public void ProcessData(Person p){....process dataConsole.WriteLine(p.ToString());}Implicit ConversionImplicit conversion takes place when there is an is-a relation between two classes, I.e., inherited from other.As per the diagram, Employee is Inherited from Person class and so that as per OOD rule, there is No need to convert Employee class to Person class. Example: Public void testdata()
{
Employee emp = new Employee();
emp.Age = 25;
emp.BirthDate = DateTime.Now;
emp.Height = "5 ' 3";
emp.salary = 2000;
emp.type = 1;
ProcessData(emp);
}When you compile and run the code, there is no error because it is Implicit conversion from child to parent.Explicit ConversionWhere there is no relation between classes and if you want to pass the object of another type to method,Then you need to convert it explicitly. ExampleConsultant cons = new Consultant(); cons.Age = 25; ....Object obj = cons; ProcessData((Employee) obj);NoteThe above code does not give any kind of compiler error, but it throws runtimeInvalidCastException if it is not able to cast to the type.Following is solution to avoid InvalidCastException at runtime because of Explicit conversion.Solution 1Catch the exception and handle it.Consultant cons = new Consultant();
cons.Age = 25;
....
Try
{
ProcessData((Employee) cons);
}
catch(InvalidCastException ex)
{
... Process exception
}Solution 2Make use of 'as' keyword of C#. It does conversion from one object to another object and returns Null If it is not able to convert. Use it when you want to convert object from one type to another object.SyntaxType t =expression as type;ExampleEmployee emp = new Employee();
Person p = emp as Person;
if(p!=null)
{ .. Process data }
else
{
.. Display error message or do another code
}Solution 3Make use of 'is' keyword of C#. It does conversion from one object to another object and returns False if it is not able to convert. Use it when you want to check whether it is convertible or not.SyntaxType t = expression is typeExampleEmployee emp = new Employee();
if(emp is Person)
{
Person p = (Person)emp;
.. Process data
}
else {
.. Display error message or do another code
}Difference between as and is
Summary'is' and 'as' keywords play an important role when we do the casting of the related objects explicitly. But you need to use it according to the situation. |
Thoughts on C#, .NET, programming, software development and productivity. Tips and tricks to solve various programming problems.
Tuesday, January 4, 2011
Casting of object and Role of 'is' and 'as' keyword
Labels:
.NET Framework
,
Casting of objects
Bind Enum to Dropdown List With Sorting
/* Create Enum Data Block First */ public enum DignosisOrderType { All = 0, General = 1, Uveitis = 2, Coag = 3, PreOp = 4, Tests = 5, RP = 6 } /* Now Creat a method to bind this drop download- pass control and Enum Data to function */ public static void BindDropDownByEnum(ref DropDownList dropDownList, Type enumDataSource) { DataTable dtTemp = new DataTable(); /*create datatable and follow the steps of ADO to bind with dropdown list */ dtTemp.Columns.Add("ID"); dtTemp.Columns.Add("Name"); string[] names = Enum.GetNames(enumDataSource); Array values = Enum.GetValues(enumDataSource); for (int i = 0; i < names.Length; i++) { DataRow drTemp = dtTemp.NewRow(); drTemp["ID"] = Convert.ToInt32((DignosisOrderType)Enum.Parse (typeof(DignosisOrderType), names[i])).ToString(); drTemp["Name"] = names[i]; dtTemp.Rows.Add(drTemp); } DataView dvTemp = new DataView(dtTemp); dvTemp.Sort = "Name"; dropDownList.DataTextField = "Name"; dropDownList.DataValueField = "ID"; dropDownList.DataSource = dvTemp; dropDownList.DataBind(); } Call Above Method BindDropDownByEnum(ref DropDownList1, typeof(DignosisOrderType)); |
Labels:
.NET Framework
How to get an object garbage collected
| Sometimes it's useful to detect when an object is garbage collected. Garbage collection happens in a separate thread, and if you want to display some info about this, in a Windows Forms GUI, you need to use BeginInvoke and not Invoke or your application will "freeze". Invoke will not be executed during garbage collection.
| ||
| |
Labels:
.NET Framework
ASP.NET Password Strength Regular Expression
ASP.NET Password Strength Regular Expression. Customize n numbers of upper case, digits, Special characters. Shown below is the regular expression for password strength with n number of digits, Upper case, special characters and at least 12 characters in length. (?=^.{12,25}$)(?=(?:.*?\d){2})(?=.*[a-z])(?=(?:.*?[A-Z]){2})(?=(?:.*?[!@#$%*()_
+^&}{:;?.]){1})(?!.*\s)[0-9a-zA-Z!@#$%*()_+^&]*$
Explanation: (?=^.{12,25}$) -- password length range from 12 to 25, the numbers are adjustable (?=(?:.*?[!@#$%*()_+^&}{:;?.]){1}) -- at least 1 special characters (!@#$%*()_+^&}{:;?.}) , the number is adjustable (?=(?:.*?\d){2}) -- at least 2 digits, the number is adjustable (?=.*[a-z]) -- characters a-z (?=(?:.*?[A-Z]){2}) -- at least 2 upper case characters, the number is adjustable | ||
Labels:
.NET Framework
,
ASP.net
Sunday, January 2, 2011
Saving Time with Snippets in Visual Studio 2010
Snippets are important to learn because they will save you time. A snippet is a set of
keystrokes that form a template for a piece of code. The code for a snippet is typically
something that is common in normal programming. You'll see many common statements
and blocks of code in this chapter, many of which have associated snippets. This section
shows you the mechanics of using snippets, and you'll see more examples throughout the
rest of this chapter.
To use a snippet, begin typing the snippet prefix until the snippet acronym appears in
the Intellisense completion list, press the TAB key twice, and fill in the snippet form while
tabbing through each field. Press ENTER when you're done.
Since you've already learned about namespaces, I'll show you the namespace snippet.
To start, open any code file and click to start typing in a part of the file outside of all code
blocks, such as directly below any using statements but above any existing namespace
statements. Type the letter n and watch the completion list go straight to the namespace
element. Type an a and you'll see the namespace alone in the completion list, as shown
in Figure 2-7.
NOTE
The CTRL-ALT-SPACE keystroke in Figure 2-7 switches between the Intellisense modes
Consume First and Standard mode. In Standard mode, which shows CTRL-ALT-SPACE,
typing characters automatically selects keywords. However, there are situations where
you are trying to type a word that doesn't exist yet and Intellisense is too aggressive by
adding the selected completion list item, instead of what you typed. In those cases, you
can press the CTRL-ALT-SPACE keys to go to Consume First mode and what you've typed will
be selected. You can still use the DOWN ARROW key on your keyboard in Consume First
mode to select the highlighted term in the completion list.
Figure 2-7 Using snippets
Figure 2-8 Filling in the Snippet template
You can identify snippets in the completion list by the torn paper icon. At this point,
you can press the TAB key to complete the namespace keyword. Then press TAB again to
produce a template where you can fill out the highlighted fields. Figure 2-8 shows the
results of creating a namespace snippet by typing n and pressing TAB, TAB.
As shown in Figure 2-8, you would type in the Namespace name in the highlighted
form field to replace MyNamespace, which is placeholder text. For templates with more
fields, you would press the TAB key to move between fields. In the case of the namespace
shown in Figure 2-8, there is only one field in the template to complete.
VB offers a couple of ways to add snippets: by typing prefixes or via a pick list. To see
how VB snippets work, place your carat inside of the Module1 module, underneath End
Main (not inside of the Main block). Type Su and press TAB, and notice that VS creates a
Sub (method) along with a template containing a field for filling out the Sub snippet.
Another way to add VB snippets is to type a ? and press TAB. You'll receive a pick list,
as shown in Figure 2-9. You can navigate this pick list to find the snippet you need, as
classified in one of the folders. VB ships with many more built-in snippets than for C#.
Now that you know how to use snippets, let's move on to the different types of
statements you can have in C# and VB and how snippets work with those statements.
Figure 2-9 VB snippet pick list
Labels:
Visual Studio
Setting Editor Options in Visual Studio 2010
The editor is very configurable, and there are more options available than many people
realize. You can view available options by selecting Tools | Options to show the Options
window in Figure 2-5. As you can see from the figure, selecting Environment | Fonts And
Colors allows you to change the appearance of VS. Regarding our current discussion of
the editor, this is where you can customize the coloration of code elements that appear
in the editor.
Most editor customizations are in a language-specific branch of the Options window.
Figure 2-6 shows the options available for C# programmers.
Most editor customizations are in a language-specific branch of the Options window.
Figure 2-6 shows the options available for C# programmers.
Figure 2-5 The Options window
Figure 2-6 C# code editor options
The Options window in Figure 2-6 is opened to Text Editor, C#, Formatting New
Lines. As you can see, there are very detailed settings for even how the editor automatically
formats new lines and where braces appear. If the code doesn't format the way you want it
to, visit this page to set the options to what you please.
Labels:
Visual Studio
Installing Visual Studio 2010
you haven't already installed VS, this section walks you through the setup process. The
guidance along the way will explain how to choose among available options to customize
the installation to your needs. The following steps explain how to install VS:
System Requirements
As of this writing Microsoft recommends you have a 32-bit x86 or 64-bit (x64) CPU,
at least 1GB RAM, a 5400 RPM hard disk drive, 3GB hard disk space, DVD-ROM,
DirectX video at 1280 × 1024 resolution, and a 1.6 GHz processor. Recommended
operating systems include Windows Vista (all versions except for Starter), Windows XP
SP2 or later (all versions except for Starter), Windows 7 (only Ultimate at the time this
chapter was written), Windows 2003 (SP1 or R2 or later), and Windows 2008 (SP1 or
R2 or later). Be sure to check Microsoft Developer Network (MSDN) online, as system
requirements can change over time.
1. When you first place the VS DVD into the drive, you'll see the Microsoft Visual Studio
2010 window, shown in Figure 1-1. Available options are to Install Microsoft Visual
Studio 2010 and Check For Service Releases. Click Install Microsoft Visual Studio 2010.
Figure 1-1 Microsoft Visual Studio 2010 Setup window
Figure 1-2 Setup Welcome window
2. The next window you'll see, Figure 1-2, is the welcome window, titled Microsoft Visual
Studio 2010. Figure 1-2 shows that I'm installing the Ultimate version. Installation for
other versions is similar, but the number of features available to install varies.
If you check the box on this page in the Help Improve Setup section, the installer
will gather logs produced during the setup process and send them across the Internet
to Microsoft after the setup is complete. To help you make an informed choice as to
whether to check this box, there is a Privacy Statement link under the check box to
click and read if you would like more information about what Microsoft does with
setup information. When you're ready, click Next. After setup components are loaded,
you'll see the licensing screen in Figure 1-3.
Figure 1-3 Setup Licensing window
3. In Figure 1-3, you'll see what components will be installed. You'll need to read the VS
license to ensure you understand what the terms are. The licensing terms can differ,
depending on what type of package you acquired and your particular country or region.
Once you've read the license, you'll need to check "I have read and accept the license
terms" to proceed. Next, enter the license key that comes with your software and enter
your name. The installer will automatically fill in the product key if you downloaded
VS via Microsoft Developer Network (MSDN). Click Next and you'll see options for
customizing product installation.
4. Figure 1-4 lets you choose between full and custom installation. If you click the
Custom option, you'll be able to choose precisely which components should be
installed. This is a good opportunity to uncheck the items you won't ever use. If this is
Figure 1-4 Setup Customization window
your first installation and you have plenty of storage, you might want to go through the
list and check everything to take a look at what is available. You can always return to
this installation later and make adjustments.
The configuration screen in Figure 1-4 shows that you can also change the location of
where to install VS. Take note of the installation location because this is where you will
go to find sample code, common assemblies, and more items affecting the development
environment. Evaluate the disk space requirements to ensure you have enough available
storage. You've now completed the configuration options for installation. Click Install to
start the installation. You'll see a screen similar to Figure 1-5 during the installation process
where the small check marks indicate which VS components have successfully installed.
Figure 1-5 Setup Progress window
5. During the installation, the VS installer will need to reboot your computer, showing the
restart message in Figure 1-6. Make sure you close any applications you currently have
open so that you don't lose your work, and then click Restart Now.
Figure 1-6 Setup Restart window
Figure 1-7 Setup Success window
6. When installation completes without error, you'll see the Success window, shown in
Figure 1-7. If you have errors during installation, this window will give you guidance
on what to do to solve the problem.
Your installation is now almost complete. You can install product documentation by
clicking the Install Documentation button, shown in Figure 1-7. The initial installation
screen that appeared when beginning the installation will reappear, as shown in Figure 1-8.
You should also check for service releases; not only for the updated functionality to VS,
but also because service releases often include important security updates.
You are now ready to run VS for the first time. At that point, you'll need to perform
one more easy configuration step, where you will choose your default environment
settings, as shown in Figure 1-9.
Checking for service releases
Figure 1-9 Default Environment Settings window
The choice you make for default environment settings depends a lot on what
language or environment you'll use to write software in.
You should now have a good installation with the configuration and environment
settings of your choosing.
Labels:
Visual Studio
Subscribe to:
Posts
(
Atom
)














