Thursday, March 31, 2016

Method Parameters in C#

In today's blog post, I will be discussing method parameters in C#. We will see the different ways in which parameters can be passed to methods in C#.

Method Parameters

Other than regular way in which we assign values to method parameters, there are a few tweaks which we can do to make our relationships with methods more useful.



Let's look at them one by one.

Optional Parameters

For any method, if we want the parameter(s) to have a default value, we can simply assign it like this:

public int Calc(int min, int max, int range = 100)
{
     \\...
}

So if any calling code passes a value for range, then that value is used. If we say Method1(1, 20, 200), then 200 is used for range's value. If we call Method1(1, 20) without any value for range, then range is used with value of 100.

This comes in handy when most of the time a default value is used but sometimes we need to pass in the value to be used for a specific parameter. We can have default values for any number of parameters, the only condition being that they come at the end after all non-default parameters.

Named Parameters

When we use our Calc() method in our code, every time we need to look at the method declaration to see the order of min, max and range. If we mess up the order while calling, we might get some wrong/ unexpected results. By using named parameters, we can assign the values for parameters based on their names instead of just the order.

So, for example, we can do:

Calc(max:20, range:80, min:1)

So this way we explicitly mention the variable name followed by the value assigned to each. This is useful to avoid any confusion which may happen when you have long list of parameters. Although, if you have a long list of parameters then you might have other issues with the code, but at least named parameters are easier to understand and less prone to error.
Another thing to keep in mind is that named arguments must appear after all fixed arguments have been specified.

Variable Number of parameters

When we want to give the caller code flexibility with the number of parameters to pass, we can use "params" keyword like this:

void VariableParamsMethod(params int[] array)
{
      foreach (var num in array)
      {
           Console.WriteLine(num);
      }
}

So here, I can call this method as :

VariableParamsMethod(1, 2);
OR

VariableParamsMethod(1, 2, 3);

I can pass in any number of int arguments and the method will work. Isn't it amazing? Internally, the compiler converts these values into array.
Also, I can pass in an integer array. That will also behave as expected.

var array = new int[4] { 1, 2, 3, 4 };

VariableParamsMethod(array);


This feature comes in handy when we want to have the flexibility of different number of parameters
to be passed.
Params can be combined with other parameters with the condition that it should be the last one and can be specified only once.

Out and Ref Parameters

When we call a method, the regular parameters are copied in the method. For value types (which I discussed here), the values are copied whereas for reference types the reference is copied, pointing to the same object in the heap.
If we want the called method to use the same variable instead of creating a separate copy, we can use the "ref" or "out" keyword.
Let's look at an example:

void OutRefMethod(out int i, ref int j)
{
     i = 5;
     j = 6;
}

So if we call the method:

int i = 1, j = 1;
OutRefMethod(out i, ref j);

At the caller side, "i" will be set to 5 and "j" will be set to 6.
This comes in handy when we want a single method to return multiple things. With ref and out parameters we can set them inside our method and retrieve at the calling side. The difference between ref and out parameter is that ref requires variable to be initialized before it is passed to the method whereas out requires the variable to be set some value inside the method. We need to mention the out and ref keywords both at method definition and method calling time to make sure that it's intentional.

Another thing to note is that if you see a lot of out and ref parameters then there might be other issues in the code (likely disobeying Single Responsibility Principle as discussed here).


Conclusion

With different types of parameters, methods can become more powerful. We can use these features as and when we need them.

For future updates to my weekly blog, please subscribe to my blog via the "Subscribe To Weekly Post" feature at the right and follow me on Twitter. Until then Happy Coding :)


Thursday, March 24, 2016

Namespaces in C#

In today's post, I will be discussing namespaces in C#. We will see how they are useful to us and some new features introduced in C# 6.

Namespace in C#

Namespaces are great for organizing classes into separate chunks. The .NET framework itself uses namespaces to organize it's huge number of classes. Even we can use namespaces to organize our classes in any fairly large project.

Namespace in C#


Using Directive

In order to access any class, we can use fully qualified name. For example,

System.Console.WriteLine("Hello World");

Or, we can access any namespace in our program using "using" directive. So if we have

using System;

at the top, then we can skip the word "System" and write our line as follows:

Console.WriteLine("Hello World");

Mostly, people prefer to write this way as it's shorter and less cluttered. In some cases, people like to write fully qualified names in order to avoid any confusion.


Namespace keyword

We can define namespace using "namespace" keyword.

namespace ns1
{
        public class cl1
        {
        }
}

namespace ns2
{
        public class cl2
        {
        }
}

In our main() method, we can use them like this:

   ns1.cl1 obj1 = new ns1.cl1();

   ns2.cl2 obj2 = new ns2.cl2();

Or use using keyword as explained above.

Namespace Alias

May times, if we have same class name in multiple namespaces and we are using both namespaces in the same file, the compiler might get confused which class are we trying to use. We can avoid such a scenario (called namespace collision) either by using fully qualified name as shown above or by using an alias like this:

using a1 = ns1.cl1;

So now we can use this alias to define our object like this:

a1 obj1 = new a1();

Static Using Directive

Since C# 6 onwards, we can use "using static" for static classes. This helps us to write only the method names directly. For example, if we use

using static System.Console;

I can directly use WriteLine() method like this:

WriteLine("Hello World");

instead of using Console.WriteLine() everywhere. So, this helps us write less cluttered code and quicker development :)

Conclusion

Namespaces are a great way for organizing our code into a more manageable manner. Having a good understanding of how to use it makes the code easy to read and understand.

For future updates to my weekly blog, please subscribe to my blog via the "Subscribe To Weekly Post" feature at the right and follow me on Twitter. Until then Happy Coding :)


Thursday, March 17, 2016

Properties in C#

In today's blog post, I will be discussing the properties in C#. We will see how properties are useful and are a great time saving feature for us.

Properties in C#

Properties are simply like the getters and setters methods which allow us to control the value being set/ read of a private variable in a class. They let you access the property as if it was a field but in reality they are special methods called accessors.

Properties in C#


In order to better understand their importance, let's look at the way we would have written some code if properties hadn't existed.


public class Employee 
{       private int employeeId;        public int GetEmployeeId()        {              return employeeId;        }        public void SetEmployeeID(int id)        {              employeeId = id;        }  }
If we had multiple properties, imagine how the lines of code would have grown.

Since properties exist, we can write it like this:

public class Employee 
{       private int employeeId;      public int EmloyeeId      {            get            {                  return employeeId;           }
          set            {                   employeeId = value;            }
      }  }


And since our accessors do not require any special logic for get and set, we can use auto-implemented properties like this:


public class Employee 
{            public int EmployeeId  {get; set;}  }

So all that lines of code are replaced by only one line as seen. This is so helpful to the developers and we use it all the time without even giving it much thought that how our task is made so much easier by the properties.

So there are two accessors: get and set. As expected, get is used to read the value of a variable and set is used to write the value. Both get and set can have different accessibility levels. If the property has only get accessor then it's a read-only property.
In the case of auto implemented properties, compiler creates a private and anonymous backing field that can be accessed only through property's get and set accessor.

Another thing worth mentioning is that from C# 6 onwards, auto-implemented properties can also have default values. Earlier, if we needed a default value, we had to manually write the code for properties accessors. But now it can be done like this:

public class Employee 
{ 
     public int EmployeeId {get; set;} = 1; 
}


So, here the default value is 1.

Conclusion

Properties help us developers to write our code quickly and efficiently. We should take full advantage of the properties instead of manually writing old style way of getters and setters. And we should thank the compiler for generating so much code for us when we use auto-implemented properties ;)

For future updates to my weekly blog, please subscribe to my blog via the "Subscribe To Weekly Post" feature at the right and follow me on Twitter. Until then Happy Coding :)


Thursday, March 10, 2016

Struct vs Class in C#

In today's blog post, we will be discussing the differences between struct and class in C#.

Struct Vs Class

Struct and Class are both constructs of the common type system in the .NET framework. Both are used to encapsulate data and behavior as a logical unit. While declaring, both look similar, except they keyword "struct" and "class" :)


Struct vs Class in C#

The major difference between struct and class is that class is a reference type and struct is a value type.  I have talked about reference vs value type before here.

A reference type is allocated on heap. It's garbage collected at frequent intervals (will cover garbage collection in another post). When a new variable is created pointing to such an existing object, no new object is created. The new reference points to the same object. So any changes made to the object using one reference is visible on the other because the underlying object is the same.

A value type is allocated on the stack. Value type is deallocated when the stack unwinds or when their containing type gets deallocated. The variable which defines the struct actually holds the data itself. When a new variable is assigned to an existing struct, a new copy of data is created and held by the new variable. So changes made to one copy are not reflected by the other.

In general, structs are limited as compared to classes. Here are some of the other differences:

  • In a struct, the fields cannot be initialized (except const or static).
  • There can be no default constructor (parameter-less constructor) or a destructor in a struct. However, structs can have constructor(s) with parameter(s).
  • Struct can be instantiated without the new operator.
  • A struct can not inherit from another struct or class. However, a struct can implement interfaces.

Conclusion

Although, most of the times, we lean towards classes as compared to structs. Classes give us more power and ease of use. Mostly people use structs for small and light-weight data.  However, it's still important to understand the difference between the two and use the right thing accordingly.

For future updates to my weekly blog, please subscribe to my blog via the "Subscribe To Weekly Post" feature at the right and follow me on Twitter. Until then Happy Coding :)


Thursday, March 3, 2016

Access Modifiers in C#

In today's blog post, I will be discussing the various access modifiers available in C#.

ACCESS MODIFIERS

The access modifiers help decide the accessibility levels of the members or types. They are the first step to learning object oriented programming. With appropriate access modifiers , we decide what is exposed and what is hidden from other parts of the code.

Access Modifiers in C#


There are 4 access modifiers:
i) Public: These is the one with least restriction. These are available for access from anywhere outside.

ii) Private: This makes sure that access is available only within the containing type. These are not available outside.

iii) Protected: Using this keyword, access is limited to containing class or any class inheriting from this.

iv) Internal: Access is limited to the current assembly. Within the assembly it can be accessed anywhere.


Protected Internal:
There is one more access modifier which is a combination of protected and internal. In my opinion, it's a little weird, because when I think of something as protected internal, I used to assume an "AND" condition between protected and internal. I thought that it should be accessible within the assembly and only containing type and derived types within the assembly should be able to access it.
But, the reality is, it's a more forgiving "OR" condition between protected and internal. So it can be accessed from anywhere within the assembly and also any derived class can also access it, even if it's outside the assembly.


Accessibility for Types

Depending on where the type or member is declared, it can be associated with different accessibility levels. If none is specified then there is a default accessibility associated.
i) Top level types: Top level types can only have internal or public accessibility. The default is internal for them.
ii) Enum: Enum members are always by default public. There is no access modifier allowed for enum members.

iii) Class: A class members can have any of the above five access modifiers associated. If no access modifiers is provided, by default, the class members are private.

iv) Interface: An interface members are always by default public. There is no access modifier allowed for interface members.

v) Struct: A struct members are by default private. They can also have public or internal access modifier.

Access modifiers are not allowed on namespaces. They are allowed only on the types mentioned above.

Conclusion

These access modifiers lay the foundation of our object oriented programming and therefore are very important to understand. Different accessibility levels allow us to expose the correct amount of functionality which is really important for security and maintainability of the application.

For future updates to my weekly blog, please subscribe to my blog via the "Subscribe To Weekly Post" feature at the right and follow me on Twitter. Until then Happy Coding :)