Tuesday, September 27, 2011

out and ref Parameters in C#

Today I am going to write about two nice modifiers that we can use when defining parameters in a method. While parameters are very simple and straight forward to use, there are tricks which can make them a lot more powerful than it seems.

C#, as well as other languages have two types of parameters. One is passing parameters 'by value' and the other is 'by reference'. The default is 'by value'. If we pass a parameter 'by value', that means we are passing a variable to a method and actually we are sending a copy of a variable instead of a reference to it. What happens here is, all the changes we do to that variable in our method, will not affect the original variable which we passed as a parameter.

If you want to pass parameters 'by reference', that's where out and ref modifiers comes in. With the help of out and the ref keyword, we can change this behavior, so we pass along a reference to the object instead of its value.

Difference between out and ref

Actually these two modifiers pretty much acts like the same. They both ensure that the parameter is passed 'by reference' instead of 'by value', but they have one significant difference. That is when we are using out parameter, before passing the variable into the method we don't have to initialize the variable. But in the method before leaving the method, we should assign a value for that. If not we will get a compile error saying "The out parameter 'x' must be assigned to before control leaves the current method".

When we are using ref parameter, before we pass the variable into the method, we must initialize it. if not we will get a compile error saying "Use of unassigned local variable".

I am going to write down a simple code, so you will be able to get a good understanding about how to use these two modifiers and their difference.

using out modifier

static void Main(string[] args)
{
     int i; //no need to assign a value to i
     Method(out i);
     Console.WriteLine(i); //i is 10
     Console.ReadLine();
}

static void Method(out int x)
{
     x = 10; //must assign a value
}

using ref modifier

static void Main(string[] args)
{
     int i = 5; //must initialize the variable
     Method(ref i);
     Console.WriteLine(i); //i is 10
     Console.ReadLine();
}

static void Method(ref int x)
{
     x = 10; //can change the value, but not a must
}

As you can see, when I am using out modifier I did not set a value to the variable before passing it. But in the method I have set a value and it is a must. When using ref modifier, I have initialized the variable and then passed it. Without initializing the variable I can't use ref and in the method, it's up to you to change the value or not. Hope you all got a good understanding in out and ref.

Feel free to give me your feedback.

Happy Coding.

Regards,
Jaliya

Friday, September 23, 2011

Named and Optional Arguments for Methods in C# 4.0

With C# 4.0, Microsoft has introduced a nice concept of this Named and Optional arguments for methods. So today I am going to write about how great this concept is.

I will start by writing down a very simple method. This method GetSum() will return the sum of two supplied values.

static void Main(string[] args)
{
     int sum = GetSum(5, 10); //5 and 10 are arguments
     Console.WriteLine(sum);
     Console.ReadLine();
}

static int GetSum(int i, int j) //i and j are parameters
{
     return i + j;
}

Please note the difference between arguments and parameters. Arguments are actual value you pass to the method when calling the method. Parameters are variables in the method declaration.

Named arguments enable you to specify an argument for a particular parameter by associating the argument with the parameter's name rather than with the parameter's position in the parameter list. Optional arguments enable you to omit arguments for some parameters. Both techniques can be used with methods, indexers, constructors, and delegates.

The general thing is when we are passing values to a method, they should be in the order same as in the parameter list. If I take above example, the values 5 and 10 are for i and j respectively. But when you use named and optional arguments, the arguments are evaluated in the order in which they appear in the argument list, not in the parameter list.

Named Arguments

Let's say in your method you are having 3 parameters. First one is int, second one is string and the third is again int. So when I am calling the method I will have to pass an integer first,string for next and again integer for the third. For that I should keep the order of parameter list in mind and of course it is a trouble. So with Named arguments, it will free you from the need of remembering or looking up the order of parameters in the parameter lists of called methods. The parameter for each argument can be specified by parameter name. I will modify the above example with Named arguments.

static void Main(string[] args)
{
     int sum = 0;

     //without using named arguments
     sum = GetSum(5, 10);

     //with named arguments
     //named arguments can be supplied for the parameters in either order
     sum = GetSum(i: 5, j: 10);
     sum = GetSum(j: 5, i: 10);

     //named arguments can follow positional arguments
     sum = GetSum(5, j: 10);

     //named argument 'i' specifies a parameter for which a positional argument has already been given
     //so the following statement causes a compiler error
     num = GetSum(5, i: 10);

     //positional arguments cannot follow named arguments
     //so the following statement causes a compiler error
     sum = GetSum(i: 5, 10);
}

static int GetSum(int i, int j)
{
     return i + j;
}


Optional Arguments

The definition of a method, constructor, indexer, or delegate can specify that its parameters are required or that they are optional. Any call must provide arguments for all required parameters, but can omit arguments for optional parameters.

Each optional parameter has a default value as part of its definition. If no argument is sent for that parameter, the default value is used.

When defining optional parameters you should keep this in your mind. Optional parameters are defined at the end of the parameter list, after any required parameters.

I will modify the first example for you to get a good understanding about this concept.

static void Main(string[] args)
{
     int sum = 0;

     sum = GetSum(5); //sum is 30
     sum = GetSum(5,20,30); //sum is 55
     sum = GetSum(5, 20); //required_i=5, optional_j=20, optional_k=15 and sum is 40

     //the following call causes a compiler error
     //because an argument is provided for the third parameter but not for the second
     sum = GetSum(3, ,4);

     //however, if you know the name of the third parameter, you can use a named argument to give a value for third
     sum = GetSum(5, optional_k: 20); //required_i=5, optional_j=10, optional_k=20 and sum is 35

     //the following call causes a compiler error
     //because the required marametr is missing
     sum = GetSum(optional_j: 20, optional_k: 30);
}

static int GetSum(int required_i, int optional_j = 10, int optional_k = 15)
{
     return required_i + optional_j + optional_k;
}

when writing your code in Visual Studio, you will notice that IntelliSense uses brackets to indicate optional parameters, as shown in the following image.

IntelliSense


Named and optional arguments, along with support for dynamic objects and other enhancements, greatly improve interoperability with COM APIs, such as Office Automation APIs. For an example, the AutoFormat method in the Microsoft Office Excel Range interface has seven parameters, all of which are optional. So it's up to you to provide optional values, if you want to change the default values.

Feel free to give me you feedback.

Happy Coding.

Regards,
Jaliya

Friday, September 9, 2011

Windows Presentation Foundation(WPF) vs Silverlight

Yesterday I did a session about Microsoft Windows Presentation Foundation in Sri Lanka .NET Forum User Group meeting and it was a great experience. Audience was really friendly and there was some nice questions from the audience. One of the interesting questions is that comparison of WPF vs Silverlight. So today I am going to write a post about Windows Presentation Foundation and Silverlight. Please note that I am getting information for my post from the msdn.

Windows Presentation Foundation(WPF)

Windows Presentation Foundation (WPF) is a next-generation presentation system for building Windows client applications with visually stunning user experiences. With WPF, you can create a wide range of both standalone and browser-hosted applications. The core of WPF is a resolution-independent and vector-based rendering engine that is built to take advantage of modern graphics hardware. WPF extends the core with a comprehensive set of application-development features that include Extensible Application Markup Language (XAML), controls, data binding, layout, 2-D and 3-D graphics, animation, styles, templates, documents, media, text, and typography. WPF is included in the Microsoft .NET Framework, so you can build applications that incorporate other elements of the .NET Framework class library.

Here is a image of sample desktop application created using WPF.

Sample desktop application created using WPF
For more information on Windows Presentation Foundation, please visit the following link.
     Windows Presentation Foundation

Silverlight

Microsoft Silverlight is a cross-browser, cross-platform implementation of the .NET Framework for building and delivering the next generation of media experiences and rich interactive applications (RIA) for the Web. You can also create Silverlight applications that run outside of the browser on your desktop. Finally, you use the Silverlight framework to create applications for Windows Phone. Silverlight uses the Extensible Application Markup Language (XAML) to ease UI development (e.g. controls, animations, graphics, layout, etc.) while using managed code or dynamic languages for application logic.

What Features are in Silverlight?

Silverlight combines multiple technologies into a single development platform that enables you to select the right tools and the right programming language for your needs. Silverlight offers the following features,
  • WPF and XAML. Silverlight includes a subset of the Windows Presentation Foundation (WPF) technology, which greatly extends the elements in the browser for creating UI. Silverlight lets you create immersive graphics, animation, media, and other rich client features, extending browser-based UI beyond what is available with HTML alone. XAML provides a declarative markup syntax for creating elements.
  • Extensions to JavaScript. Silverlight provides extensions to the universal browser scripting language that provide control over the browser UI, including the ability to work with WPF elements. 
  • Cross-browser, cross-platform support. Silverlight runs the same on all popular browsers (and on popular platforms). You can design and develop your application without having to worry about which browser or platform your users have.
  • Access to the .NET Framework programming model. You can create Silverlight applications using dynamic languages such as IronPython as well as languages such as C# and Visual Basic.
  • Tools Support. You can use development tools, such as Visual Studio and Expression Blend, to quickly create Silverlight applications.

For more information on Silverlight, please visit the following link.
     Silverlight

WPF compatibility with Silverlight 4

As I told you before Silverlight offers a subset of the functionality provided by Windows Presentation Foundation (WPF) and enables you to build rich Internet applications that are easy to deploy and quick to install. An additional goal for Silverlight is to enable you to transfer your .NET Framework development experience to Silverlight, and vice versa. You should also be able to port Silverlight applications to the desktop, mainly reusing the XAML.

Since there is a lot of things about this in the msdn site, I will just provide the link. So you all can go through it.
     WPF compatibility with Silverlight 4

Hope you all got a good understanding about Windows Presentation Foundation and Silverlight. Please feel free to give me your feedback.

Happy Coding.

Regards,
Jaliya

Wednesday, September 7, 2011

What is Web 1.0, Web 2.0 and Web 3.0

Today after sometime of silence, I am going to write about these three categories in Web applications. Actually I happened to know about these categories today and thought it's better if write a post about it. So I will start with Web 1.0.

Web 1.0 - Websites, E-mail Newsletters

It's hard to define Web 1.0 for several reasons. So I will put it this way. What Web 1.0 really is, it's everything in between from the day World Wide Web has introduced and the day Web 2.0 has introduced. So keeping that in mind, Web 1.0 category web applications contains following features.
  • Web 1.0 sites are Static.
  • Web 1.0 sites aren't Interactive.
  • Web 1.0 applications are Proprietary.
  • Web 1.0 sites are One-way.
  • Web 1.0 sites are Passive.
  • Web 1.0 sites are Closed.

Web 1.0 category sites basically contains information that user's might find useful, but there's no reason for a visitor to return to the site later. An example might be a personal Web page that gives information about the site's owner, but never changes. And visitors can only visit these sites, they can't contribute to these sites. Because of this, these kind of sites are Static and they are not Interactive to the visitor which will make the site  a Passive, One-way and a Closed site.

Web 2.0 - Blogs, Wikis, and Social Networking sites

At its core, Web 2.0 is the beginning of two-way communication in Web Applications. Web 2.0 sites invite participation and that might be voting, rating, commenting and submitting new posts. So Web 2.0 sites are collaborative. For example in Social networking sites like Twitter, Facebook you can have friends, fans, followers, connections etc. So Web 2.0 category sites contains following features.
  • Web 2.0 sites are Two-way.
  • Web 2.0 sites are Active.
  • Web 2.0 sites are Dynamic.
  • Web 2.0 sites are Collaborative.

Web 3.0 - Mobile Websites, Text Campaigns and Smartphone Applications

Web 3.0 is all of the above with web experience that is no longer limited to desktop and laptop computers. It’s the Internet on the go fueled by mobile phones and tablets. Websites must be designed to be easily read on mobile devices. Group text campaigns function like e-mail newsletters in Web 1.0 which will drive traffic to your mobile website. Smartphone Applications enable content to be published and shared easily while on the go.

So I hope you all got some understanding about these categories. With such a rapid growth in technology and with the combination of Web 1.0, Web 2.0 and Web 3.0, you will soon face a day that you feel the world is in your hands.

Happy Coding.

Regards,
Jaliya