Showing posts with label .NET Concepts. Show all posts
Showing posts with label .NET Concepts. Show all posts

10 May 2015

why string are called immutable in c#

You have often heard strings are immutable and if you are wondering why "strings are called immutable", then you are reading the right article on this page.

Immutable in English means, "unchangeable" and it has the same meaning in c#.net well.

string loan1 ="Housing Loan";
string loan2 = loan1;

// Update the string value
loan1 =loan1+ " And loan to buy car";

After assigning a new value to the string variable 'loan1', the reference where it points to has been changed. This is demonstrated by making use of address(&) operator in Visual Studio Quick Watch window.

C#.NET program showing why strings are called immutable

With each string value update, string variable address is changing. This means the original "string" value is not getting updated with each update, instead, a new string is being created and the new address is assigned to the string variable. This is why strings are called immutable.

25 December 2013

c# methods explained in detail

When programming you use classes, methods, properties and data members, etc. In this tutorial let's discuss methods in C# language.

  1. What is a method?
  2. What constitute a method?
  3. A typical method in C# language
  4. Types of methods

What is a method?

A method usually performs something when it is invoked. What a method performs, depends on what logic you put in the method body.

For example, consider a Car class; We can define Drive() method to drive the car forward and Reverse() method to go reverse. Here both Drive() and Reverse() methods perform some actions, they modify the state of the object. i.e., Car position.

Consider a Television set's remote control example; It controls the behaviour of the television. You can implement VolumeUp(), VoulmeDown(), ChangeChannel() and ScanChannels(), etc, methods to control the behaviour of the TV.

What constitutes a method?

  1. Method name:

    Used to identify a method and invoke the method.

  2. Method arguments or parameters:

    A method can have multiple or no parameters. Method arguments can be of different types based on your requirements.

  3. Method body:

    Method body defines the behaviour. It is the crux of the method.

  4. Method return type:

    A method can return a single entity or its return type can be void, returning nothing

  5. Method access specifier:

    Used to define the visibility of the method. Using method access specifier developer defines, who can invoke the method and who cannot invoke it. It can be any of the C# access specifier i.e., private, internal, protected, internal or protected internal.

  6. Method name, argument list, return type and access specifier together forms the method signature.

A typical method in C# language

As always going through an example is better idea to understand something new. Let's consider the below C# class, Calculator.
public class Calculator
{
    public long Add(int a, int b)
     {
       // method logic...
       int sum = a+b;
      
      // Method is returning
       return sum;
     }
}
In the above C# code example, Calculator is a class and has a method Add().
  1. Add is a method name.
  2. (int a, int b) is an arguments list. Where a & b is parameters of integer type.
  3. What you can see within the { flower brackets } is method body.
  4. At the end of the method body, there is a return statement, returning sum. Method execution stops when the control flow in a method encounters a return statement.
  5. The Add() method has public access specifier, meaning anybody who can use the class can invoke the method. i.e. It's visible to all.

Types of methods

There are different method types. Let's go one by one briefly:
  1. Instance methods
  2. Static methods
  3. Constructors & Destructors methods
  4. Abstract & concrete methods
  5. Virtual & overridden methods
  6. Overloaded methods
  7. Partial methods
  8. Extension methods

Instance methods

Method which can only be invoked using class instance are called instance method. i.e., in the above Calculator class, the Add() method can be invoked using the instance.

Calculator calculator = new Calculator();
long sum = calculator.Add(100, 200);

Static methods

Methods can be declared static, meaning using class itself such method can be invoked. Using class instance such methods cannot be invoked.

Always declare a method as a static method, if doesn't use any instance members. Static methods perform little better compared to instance methods.

Let's add a static method to the Calculator class and see how it can be invoked.

public class Calculator
{
    public static void DisplayManufacturer()
     {
      Console.Writeline("Casio");
     }
}
  // static method invoked using the Calculator class.
  Calculator.DisplayManufacturer();

Constructors & Destructors methods

Constructor and Destructors are also method in the class, but they are special methods. Constructors are used to create an instance of a class and Destructors used to destroy the objects.

Constructors can have one, multiple or no parameters. The Constructor without any parameter is referred as default constructor. Even if the developer doesn't define a parameterless constructor they exist by default. Constructors don't have a return type; their return type is implicit. i.e. It can only return the same class object.

public class Calculator
{
   public string Model{get;set;}
   public Calculator(string model)
     {
        this.Model = model;
     }
}

// Instance created using the parameterless constructor.
Calculator calculator= new Calculator();

// Instance created using the parameter constructor.
Calculator calculator= new Calculator("2012-FC");

Destructors are also called finalizers. Destructors cannot have any parameters. In C# .NET they cannot be invoked by developers, they get invoked by the framework during the Garbage collection process.

Let's consider an example of Destructors with the same Calculator class:

public class Calculator
{
   // Finalizer method
   ~Calculator()
     {
       
     }
}

Abstract & concrete methods

Abstract methods are declared as abstract and just have method declaration. The abstract methods will not have method definition or method body. A class containing a abstract method should be declared a abstract class. In the C# code sample, the Car class has the Drive() method which is an abstract method.

public abstract class Car
{
   public abstract Drive();
}

The method which has the definition or provide implementation are called concrete methods. In this post, the Caluculator class's Add() method is an example of concrete method.

Virtual & overridden methods

Methods can be declared as virtual; meaning such method can be overridden in the derived class. When writing a class if you think derived class can customize the behavior then mark the method as virtual.

Methods declared virtual in derived class, can be overridden by the derived class to customize the behavior accordingly.

Refer article, Function overriding in C# .NET for more details on Virtual & overridden methods

Overloaded methods

Method can be overloaded in a class or struct to achieve compile time polymporphism. Methods with the same name and varying parameter list by number and data types of arguments are called overloaded methods.

Partial methods

Partial methods can be declared in one partial class and have implementation in another same name partial class. Partial methods are introduced for situations where you are generating code automatically using tools.

Refer another detailed tutorial on partial methods in C# .NET to know in detail.

Extension methods

Extension methods adds a method to class without modifying the class definition, so it's useful in adding method to a third party class within a namespace scope. To understand more go through tutorial on C# extension methods.

11 December 2013

[Debugger Display] attribute in C#.net explained

Today let's know one tip to make debugging the code is a lot easier using [DebuggerDisplay] attribute in C# .Net by going through below topics:

  1. Introduction to Debugger Display attribute
  2. Attributing classes with [Debugger Display] attribute
  3. [Debugger Display] attribute uses
  4. Debugger display attribute and coding standard

Introduction to Debugger Display attribute

The code is written once, whereas code will be debugged and read many times. To understand the code sometimes we all debug it. Hence it makes life easier and improves developer productivity when debugging is made easy.

One such option to improve debugging is by using [DebuggerDisplay] attribute. Let's see how we can use the debugger display attribute to make debugging .net code in visual studio easier.

Attributing classes with [Debugger Display] attribute

Let's consider the below employee class to understand debugger display attribute with an example.
[DebuggerDisplay("Id={Id}, Name={Name}, Department={DepartmentId}")]
public class Employee
{
  public string Id {get;set;}
  public string Name {get;set;}
  public Money Salary {get;set}
  public string DepartmentId{get;set;}
}

[Debugger Display] attribute uses:

Let's consider you are writing employee repository code, which possibly could look like below:

  Employee employee = Repository.Get("1234567");

While you debug, mouse over on the employee variable, you will get to see objects Id, Name & Department values like below. By looking at the values, we can easily decide whether the repository code is working as expected or not.

debugger display attribute

Without attributing debugger display attribute to classes, you have to use either the Immediate window or the Quick watch window, which takes one or more extra steps.

Debugger display attribute and coding standard

Now, we know the advantages of Debugger display attribute to enhance the debugging experience and make it easier. So it makes sense, to apply this attribute to classes for displaying key properties. Developer should always use the debugger display attribute while creating new entities, i.e. class, structures.

And also as part of the code review process the addition of new classes should be checked to see whether debugger display attribute is applied appropriately or not.

Having said this all, inclusion of applying Debugger Display to classes should be made part of the standard coding standard document.

06 December 2013

Sealed class explained

In this programming tutorial let's understand what is a sealed class by going through the below topic on sealed class:

  1. What is sealed class
  2. How to define a sealed class
  3. Sealed classes .NET framework
  4. Singleton design pattern & sealed class

What is sealed class

Inheritance is one of the building block of the OOPS. However sometimes, allowing a class to be inherited doesn't make sense. In such circumstances, we can make the class cannot be inherited. C# .NET, has exposed a keyword, "sealed", to make a class cannot be inherited. So in essence, the class which cannot be inherited are called Sealed class.

How to define a sealed class

public sealed class BaseClass
{
}
As you can see above in the above C# code sample, the keyword "sealed" is used to make the BaseClass as sealed class.

Sealed class .NET framework

string (System.String) is a sealed class.

Making singleton as sealed class

02 November 2013

[Flag] attribute on enumeration explained

To understand new stuff it's better idea to start with an example. So let's not wait and go through below:

  1. Introduction to Enumeration marked with Flag attribute with example
  2. Solution: Enumeration with [Flag] attribute
  3. Important facts about enumeration marked with Flag attribute
  4. Working with Flag enumerations

Introduction to Enumeration marked with Flag attribute with example

Think you are working on class level design to build, a user interface to manage permission to users on the system. The available permission is View permission, Create permission, Update permission & Delete permission. A user having View permission can also have other permission as well. So users can have multiple permissions all at the same time.

To accommodate the above requirements we can think of a permission as enumeration having different defined values.

public enum PermissionType
{
   View,
   Create,
   Update,
   Delete
}

public class User
{
 public string Name {get; set;}
 public PermissionType Permission {get; set;}
}
The "User" class has a member of type "PermissionType" enum, to represent the permissions the user object has been granted.
User newUser = new User();
newUser.Permission = PermissionType.View;

Loking at the code, User class object can be assigned with only one permission at a time. Then how can User class object represent multiple permissions all at the same time? To achieve this, User class can maintain an array of PermissionType enumeration. That's not bad, but we have elegant solution to the problem.

Solution: Enumeration with [Flag] attribute

Let's modify the PermissionType enumeration by marking with Flag attribute

[Flag]
public enum PermissionType
{
   View =1,
   Create =2,
   Update =4,
   Delete =8
}

With Flag attribute on the enumeration we can assign multiple permission to User class object all at the same time. The individual Flag attributed enumeration permission types will be separated by pipe (|) symbol.

User newUser = new User();
newUser.Permission = PermissionType.View | PermissionType.Create 
                   | PermissionType.Update;
go top

Important facts about enumeration marked with Flag attribute

Flag Enumeration values binary representation and resultant values
  1. As you can see, the individual values View, Create, etc in the flagged enumeration have been assigned with 1, 2, 4, 16. These values are not random there are in the order.
  2. The first value View is nothing but 20 = 1 and second value Create = 21 = 2
  3. Similarly, the third value Update = 22 = 4 and Delete = 23 = 8
  4. That means, the enumeration marked with Flag attribute values should be 2X, where X being 0, 1, 2, 3, ..., N

Working with Flag enumerations

You can use the HasFlag() method to check whether given flagged attribute value has any of the defined values.
User newUser = new User();
newUser.Permission = PermissionType.View | PermissionType.Create 
                    | PermissionType.Update;
if(newUser.Permission.HasFlag(PermissionType.Create))
{
   // User has Create Permission
}

14 May 2013

on exception behavior inside using statement block

In another post discussed about prerequisite to use "using" keyword. Now let's discuss more on using statement block and exception inside them on C# .NET.

C# .NET interview question on using statement block:

Will the Dispose() method gets invoked on an exception inside the using statement block?. Let's have a look at "using" keyword program demo code in C# language.

namespace UsingKeywordInterviewQuestion
{
  // Class implemented the IDisposable interface
  public class ClientManager: IDisposable
  {
    public void Dispose()
    {
   Console.WriteLine("Called IDisposable.Dispose() method");
      // Keep the console window open
      Console.ReadLine();
    }
  }
}
class Program
{
 public static void Main(string[] args)
 {
   using (ClientManager clientManager = new ClientManager())
   {
    // Exception occurred inside the using statement block
     throw new Exception();
   }
  }
}
Let's have look at demo code console output:
Unhandled Exception: System.Exception: Exception of type 'System.Exception" was thrown.

at Program.Main(string[] args) in D:\Tutorial\UsingStatement\Program.cs line 13

Called IDiposable.Dispose() method

Analysis of the "using" statement block sample code and its output.

Even when an exception occurred inside the using statement block, the respective class Dispose() method will get invoked.

17 April 2013

What is type safety in C# .net

When reading about the advantages of using generics, you will come to know you can write type-safe collections and these are the collections which avoid boxing and unboxing.

After reading such statements if you are getting questions on type safety, then you are in the right place to understand about type safety concept.

Let's try to find the answers for the below questions on type safety:

  1. What is type safety in .net?
  2. When does the type safety check happen and who ensures the type safety in .net?
  3. How type safety checks makes developer life easy?

Now let's find the answers for the type safety questions:

What is type safety in .net?

Type safety prevents assigning a type to another type when are not compatible.
public class Employee{}

public class Student{}
In the above example, Employee and Student are two incompatible types. We cannot assign an object of employee class to Student class variable. If you try doing so, you will get an error during the compilation process.

Cannot implicitly convert type 'Program.Employee' to 'Program.Student'.

As this type safety check happens at compile time it's called static type checking.

public class Employee {}
public class Engineer : Employee {}
public class Accountant : Employee {}

public static void Main(string[] args)
  {
   Accountant accountant = new Accountant();
   Engineer engineer = (Engineer)(accountant as Employee);
  }

In the above example, Engineer and Accountant class derives from the same Employee base class. When tried to type cast object of Accountant class to Engineer class variable, it throws System.InvalidCastException at runtime:

Unable to cast object of type 'Accountant' to type 'Engineer'.

Above type checking happens at runtime, hence it is called runtime type checking.

When does the type safety check happens and who ensures the type safety in .net?

As discussed type safety check happens both at Compile time and at runtime. The compiler will do the compile-time type safety check and CLR will do the runtime safety check.

How type safety checks makes developers life easy?

The advantages of type safety are pretty straightforward.

At compile time, we get an error when a type instance is being assigned to an incompatible type; hence preventing an error at runtime. So at compilation time itself, developers come to know such errors and code will be modified to correct the mistake. So developers get more confidence in their code.

Run time type safety ensures, we don't get strange memory exceptions and inconsistent behavior in the application.

You might be interested in my recent blog posts as well:

Events in C# .NET tutorial: What are events, when to use events, etc

Delegates in C# .NET tutorial: Delegates explained in detail

Generics delegates in c#

Dependency Injection explained