Showing posts with label .net framework. Show all posts
Showing posts with label .net framework. Show all posts

Misconceptions regarding Pass By Value and Pass By Reference in C#

Udemy

Introduction:

It is a common question which is asked by interviewers in interviews that "What is Pass By Value and Pass By Reference" or "What is the difference between Pass By Value and Pass By Reference". Most of the beginner level developers and also many of intermediate level developers have misconception on it and they answer it wrong during interview.

When i didn't knew that real difference, i used to answer it like, when we pass primitive types they are passed by value but when we pass reference type, they are passed by reference which i was not aware that it is wrong.

So, today i decided to write on this topic so that readers reading my blog could be aware of the real difference and they can correct their misconception regarding it.

Pass By Value in Value Types:

In .Net Framework all objects are by default passed by value not passed by reference either it is a Value Type (so called Primitive types like int,char,double etc) or Reference Type (class,interface,delegate,string etc).

I will not go in to the details of Value Type and Reference Type definition and concept, you can read about them here.


Consider the following Examples:


First i will show a example using Value Type.

int num1 = 5;
int num2 = num1;
num2 = 10;

Console.WriteLine(num1);



So what will be printed on Console?

If your answer is 5,then you are right, because int is a value type, it is passed by value, which means for the above code num1 has 5 stored in it, when we create num2 and assign it num1 value of num1 is copied to num2 and after that if we change num2 it will not affect num1, ofcourse because we have copied value of num1 to num2, why num1 is to be change.

The same happens when we pass value types to methods. For Example:

We have created a method with sets the value of a int variable to 10.

private void ChangeValue(int i)
{
   i = 10;
}



Now we call it using our previous example:

int num1 = 5;

ChangeValue(num1);
           
Console.WriteLine(num1);



What would be the output on Console now?

Yes it will still output 5 as i already said that value is copied, so when ChangeValue method is called, num1 variable value is copied to i  so changing i does not changes num1.

Diagrammatic/Pictorial Representation of Pass By Value in Value Types: 

 

Here is diagrammatic representation of Pass By Value.




Pass By Value in Reference Types:

 I have following class of User which is a reference type as classes are reference types :

public class User
{
    public int UserID {get;set;}
    public string Name {get;set;}
}



we create an instance and set its properties then we assign it to another instance and change Name property and then we print Name on Console to check what is printed:

User objUser = new User() 
{ 
     UserID = 1, 
     Name = "Ehsan Sajjad" 
};

User objUser2 = objUser;
objUser2.Name = "Jon Doe";



When we create Instance of class User, an object is create in memory(Heap) and memory is allocated to it and we are storing reference to that memory location in objUser reference memory (mostly Stack) so that we can use it further, otherwise it will get lost in the memory so we need to keep a reference to it for doing different operation in memory.

When we assign objUser to objUser2 reference of object memory location which objUser is holding copied to objUser2 , now we have two seperate copies of reference but they are both are pointing to same memory location which means they both are referencing to same memory location,so changing the value  of Name property will change the value in the object in memory of which we have  reference in objUser and objUser, hence "Jon Doe" will be printed on console and it will be reflected in both references.

Diagrammatic/Pictorial Representation of Pass By Value in Reference Types:




We can see the same behavior using a method,see the following method to change Name property of User object:

public static void ChangeName(User user)
{
    user.Name = "Jon Doe";
}


We call it to change the object state, it will give the same behavior what we saw in assignment case:

User objUser = new User() { UserID = 1, Name = "Ehsan Sajjad" };

ChangeName(objUser);

Console.WriteLine(objUser.Name);



When we are passing reference objUser of User object to method ChangeName, reference of memory location is copied to the local object user of method but they are both are pointing to same memory location which means they both are having reference to same memory location,so changing the value the value of Name property will change the value in the object in memory of which we have  reference in objUser and user, hence "Jon Doe" will be printed on console.


Here is diagramatic representation of it:





When the ChangeName(objUser) is called, as it is referring to same memory location, it will modify the Name property of User object to "Jon Doe".





But think about what would happen if i set the user to null inside ChangeName method like:

public static void ChangeName(User user)
{
    user = null;
}


and now we call it for objUser :

User objUser = new User() 
{ 
     UserID = 1, 
     Name = "Ehsan Sajjad" 
};

ChangeName(objUser);
Console.WriteLine(objUser.Name);


If you are thinking that it will throw Null Reference Exception, then you are wrong, and if you are thinking that it will output Ehsan Sajjad, then you are right and you have understood that reference are passed by value in C# not by reference.

See the pictorial representation to understand better:

 

 

Pass By Reference:

If we want to make objUser null, we will have to pass it to the method via reference which is done in C# using ref Keyword. We will use the above examples again but this time we will pass them by reference and will see what happens so that we can inderstand the difference between these two.

Pass By Reference in Value Types:

We will use the same above example but this time we will be passing by reference. For that first of all we have to change the method signatures of method ChangeValue(int i) to ChangeValue(ref int i), we have added ref keyword with the input parameter which means that when calling this method the argument should be passed by reference to it:
private void ChangeValue(ref int i)
{
   i = 10;
}

 Now we will use the same code as above but we have to use ref keyword at calling side for the parameters that method expect to be passed by reference otherwise you will get compile time error, and your code will not build:

int num1 = 5;

ChangeValue(ref num1);
           
Console.WriteLine(num1);
This will output 10 on the screen, because we are using ref keyword, in the above code when ChangeValue is called the incoming parameter of it has the same memory address of num1 which is passed as argument that's why now modifying the value of i would reflect the change in num1 as well, in pass by reference new memory location is not used for the method parameter so changing the value of it will reflect the variable that is passed from calling side.

Pass By Reference in Reference Types:

We will now check the same thing with reference types, and the behaviour would be same for reference types case as well,first modify the signature of method so that it takes parameter as reference:
public static void ChangeName(ref User user)
{
    user = null;
}


and we will call it simply this way:

User objUser = new User() 
{ 
     UserID = 1, 
     Name = "Ehsan Sajjad" 
};

ChangeName(objUser);
Console.WriteLine(objUser.Name);



Now when we will call it on objUser setting user to null inside ChangeName will also make objUser null because instead of passing the reference by value (in that a new reference memory location is create which points the same object) it is passed by reference, so in this case new copy of reference is not created but the reference of objUser is passed to method which results setting the calling side reference to also change the memory location where it is pointing.



Difference between static and sealed class in c#

Udemy

What is static class

A static class is very similar to non-static class, however there's one difference: a static class  can't be instantiated. In different words, you can not use the new keyword to make a variable of that class type. As a result of there's no instance variable, you access the static class members  by using class name. 

For Example,we have following static class which has a static method which adds two number.This is just as example, we already have a Math class in System namespace which framework has provided which has all the commonly used Math functions available:


public static class MathUtility
{
  public static int Add(int a, int b)
  {
   return a+b;
  }
}


We can call it this way:


int result = MathUtility.Add(2,5);


A static class will be used as a convenient instrumentation for sets of ways that simply treat input parameters and don't got to get or set any internal instance fields. for instance, in the .NET Framework class Library, the static System.Math class contains functions/methods that perform mathematical operations, with none demand to store or retrieve knowledge that's distinctive to a specific instance of the Math class. That is, you apply the members of the class by specifying the class name and also the methodology name, as shown within the following example.



double dub = -3.14;
Console.WriteLine(Math.Abs(dub));
Console.WriteLine(Math.Floor(dub));
Console.WriteLine(Math.Round(Math.Abs(dub)));

Output:

3.14

-4

3


As is that the case with all class types, the data for a static class is loaded by the .NET Framework common language runtime (CLR) once the program that references the class is loaded. The program cannot specifically tell when the class is loaded. However, it's certain to be loaded and to own its fields initialized and its static constructor referred to as before the class is documented for the primary time in your program. A static constructor is called just once, and a static class remains in memory for the time period of the applying domain during which your program resides.



Features of Static Class:

  1. It can only have static members.
  2. It cannot have instance members as static class instance cannot be created.
  3. It is a sealed class.
  4. As static class is sealed, so no class can inherit from a static class.
  5. we cannot create instance of static class that's the reason we cannot have instance members in static class, as static means shared so one copy of the class is shared to all.
  6. static class also cannot inherit from other classes.


What is sealed class


A sealed class cannot be inherited(means it cannot be used as a base class). It stops/restricts other classes from inheriting from it. Yes, when a class is marked sealed no other classes could inherit from it.

Consider the following example in which  class SealedClass inherited from class BaseClass but as we have marked SealedClass sealed using sealed modifier, it cannot be used as base class by other classes.

Consider the following example:

class BaseClass 
{

}    

sealed class SealedClass : BaseClass
{

}

We can also make methods and properties sealed. We can also mark overridden methods or properties  of base class in child class sealed so that they cannot be overridden further sub-classes that inherit from this subclass.

class A
{
 protected virtual void Foo()
 {
  Console.WriteLine("A.Foo");
 }

 protected virtual void Bar()
 {
  Console.WriteLine("A.Bar");
 }
}

class B : A
{
 sealed protected override void Foo()
 {
  Console.WriteLine("B.Foo");
 }

 protected override void Bar()
 {
  Console.WriteLine("B.Bar");
 }
}

Now see this :

class C : B
{
 // Attempting to override Foo causes compiler error CS0239. 
 // protected override void Foo() { Console.WriteLine("C.Foo"); }
 // Overriding F2 is allowed. 
 protected override void Bar()
 {
  Console.WriteLine("C.Bar");
 }
}

you cannot use abstract and sealed modifier together with a class because abstract class has to be inherited by some sub-class that gives implementation of  abstract methods/properties.

Also when using sealed modifier with methods/properties that method should be override.In .Net Framework structs are implicitly sealed which means they cannot be inherited.

Some run-time optimization are also done when sealed class members are called, so calling of  sealed class members is slightly faster than other.

The following are the points to keep in mind about sealed class:

  1. sealed class can be instantiated.
  2. It can inherit from other classes.
  3. It cannot be inherited



Extension Methods Feature in C# with Simple Example

Udemy

Introduction:


Extension methods are special type of methods which were introduced in C# 3.0. They are used to extend the functionality of  any existing type in .Net.Using extension method we can add new methods to a class/type without modifying original source code of  Type, recompiling, or creating a new derived type.

Normally when we use linq standard query operators that add query functionality to the existing IEnumerable and System.Collections.Generic.IEnumerable<T> types. For using the standard query operators,first bring them in scope by writing using System.Linq in the code file.

Now you can call for example GroupBy,OrderBy etc like instance methods on any type that implement IEnumerable<T>

According to MSDN :


Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type. For client code written in C# and Visual Basic, there is no apparent difference between calling an extension method and the methods that are actually defined in a type.

Syntax of writing Extension Method :


As extension method is a special method, it is defined little differently than normal method.Here is the points to be noted when writing extension method:

  1. It should be a static method.
  2. It should be written in a static class.
  3. its first parameter starts with this keyword followed by type parameter
  4. Extension method should be in the same namespace otherwise you will need to inculde namespace of the class with a using statement. 

Simple Example:


We can write extension method for any existing type in our code.Most of the time we write extension method for types that we cannot modify which are built-in in the .Net Framework.

I will make a simple extension method on string type to convert string to integer.


public static class StringExtensions
{
 public static int ToInt32(this string value)
 {
  int result;
  if (int.TryParse(value, out result))
  {
   return result;
  }

  return 0;
 }
} 

and we can use it to convert string to integer if string contains numeric value in. We can call it this way:


public class Program
{
 public static void Main()
 {
  
  Console.WriteLine("123".ToInt32());
  
 }
}

You can see running example in  this fiddle





Translate C# code to JavaScript in Visual Studio using DuoCode

Udemy
I have just seen this interesting thing that is launched with Roslyn Compiler in C# 6 which is that we can now write code in C# and Roslyn Compiler will translate it in to JavaScript for us.It is a tool for compiling JavaScript without actually writing JavaScript.

It allows developers to develop Html5 applications using C# and .Net Framework inside the Visual Studio IDE.

It also supports many C# features including Class Inheritance,strong typed classess,generics, Linq, Lambda Expressions, Reflection

The name of this is DuoCode. It is also called Cross Compiler as it cross compiles C# code in to JavaScript.


DuoCode is a fully-featured C# compiler, powered by Microsoft® Roslyn, and integrated in Visual Studio.

It cross-compiles your C# 6.0 code into high-quality readable JavaScript code, enabling rapid development of web applications utilizing the extensive features of the C# language, the Visual Studio IDE, and the .NET Framework base class libraries.

It automatically generates source mappings which allows developers to see and debug C# code inside the browser in Visual Studio 2015.

This feature allows developers do full debugging of C# code using browser Developer tools which includes breakpoints, step in, step over , watch etc.

You can see live working sample here and here is the official site of DuoCode

It is available as Visual Studio Extension in Visual Studio Gallery with title DuoCode for Visual Studio and is also available as Nuget Package. It is automatically added to the project when creating project from the template.

For adding in existing project run Install-Package DuoCode -pre from Nuget Package Manager Console.



Sql NOT IN operator in LINQ query Entity Framework

Udemy
Few days ago, i came across a scenario in which i needed to apply sql NOT IN operator in my project as LINQ Query, my project was in mvc and i used ADO.net Entity Data Model to interact with database.


Here is the sql query which i needed to convert to linq:


SELECT d.processid,d.name,t.test_name
FROM dc_tp_tprocess d
left outer join dc_tp_tprocedured pd on pd.processid=d.processid
left outer join dc_tp_test t on t.procedureid=pd.procedureid
where d.active='Y' and t.testid=1 
                   and d.processid not in (1,2,6,8,9,10)
order by t.testid,d.processid 


At last after posting my question on a forum i got an answer from some one and that was this:


int[] tmp=new int[]{1,2,6,8,9,10};

var query=from d in dc_tp_tprocess
          join pd in dc_tp_tprocedured on d.processid equals pd.processid&nbsp;
         into leftGroup1
          from pd in leftGroup1.DefaultIfEmpty() 
          join t in dc_tp_test on pd.procedureid equals t.procedureid&nbsp;
          into leftGroup2
          from t in leftGroup2.DefaultIfEmpty()
          orderby t.testid,d.processid
          where d.active=="Y"&nbsp;
         &amp;&amp; t.testid==1&nbsp;
         &amp;&amp; !tmp.Contains(d.processid)
          select new {d.processid,d.name,test_name=t==null?"":t.test_name}; 


The tmp is a temporary array taken from which i am checking that the processID coming in the current row not exists in that array then select row.

I hope it will help if you stuck or got same scenario and don't getting how to handle the situation -:).



How to Deserialize Xml using LINQ

Udemy
Binding XML data to Model in C# MVCToday i saw a SO question where OP had xml in a string and OP wanted to deserialize to its specifc type using linq.

Here is the xml:


<people>  
            <person>
                <name>Mr Brown</name>
                <age>40</age>
                <hobby>
                    <title>Eating</title>
                    <description>eats a lot</description>
                </hobby>
                <hobby>
                    <title>Sleeping</title>
                    <description>sleeps a lot</description>
                </hobby>
            </person>
            <person>
                <name>Mr White</name>
                <age>40</age>
                <hobby>
                    <title>Skiing</title>
                    <description>more details on this</description>
                </hobby>
                <hobby>
                    <title>Football</title>
                    <description>watches football</description>
                </hobby>
            </person>
            </people>

First of all we need to create class type in which the data will be deserialized.We have main node people so our one class will be People with three properties Name,Age and Hobbies.As hobbies can be multiple of a person we will need a collection of hobbies and you can observe that from the xml as well that person have multiple hobbies and of course i also have many hobbies..:)


here it is:


public class People
        {
            public string Name { get; set; }
            public string Age { get; set; }
            public IList<Hobby> Hobbies { get; set; }
        }
        public class Hobby
        {
            public string Title { get; set; }
            public string Description { get; set; }
        }

First of all i will load the string xml in to XElement :


string xml = @"<people>  
            <person>
                <name>Mr Brown</name>
                <age>40</age>
                <hobby>
                    <title>Eating</title>
                    <description>eats a lot</description>
                </hobby>
                <hobby>
                    <title>Sleeping</title>
                    <description>sleeps a lot</description>
                </hobby>
            </person>
            <person>
                <name>Mr White</name>
                <age>40</age>
                <hobby>
                    <title>Skiing</title>
                    <description>more details on this</description>
                </hobby>
                <hobby>
                    <title>Football</title>
                    <description>watches football</description>
                </hobby>
            </person>
            </people>";

XElement element=XElement.Parse(xml);

Now we will write linq query to deserialize the xml. Here we go:


var person = from a in element.Descendants("person")
             select new People
             {
              Name = a.Element("name").Value,
              Age = a.Element("age").Value,
              Hobbies = a.Descendants("hobby")
                         .Select(x => new Hobby
                                 {
                                  Title = x.Element("title").Value,
                                  Description = x.Element("description").Value
                                 }).ToList()
                            };
  
foreach(var d in person)
{
  
  Console.WriteLine(String.Format("Name = {0}:Age={1}:Hobbies:{2}",d.Name,d.Age,d.Hobbies.Count()));
  
}

Here is theWorking Example on DOT NET FIDDLE of the code.


Cheers! Happy Coding.

Stackoverflow Reference Question:

Binding XML data to Model in C# MVC