Introduction to IEnumerable and IEnumerator in C#


IEnumerable and IEnumerator are standard interfaces defined in C# which are used to enumerate the both generic and non-generic collections and we can iterate over these collection in forward only manner. Both are very related with each other in working in the .Net Framework.

 IEnumerator:

IEnumerator defines the way in which to traverse the elements of the collection in forward-only manner. The definition of IEnumerator contains just one property named Current which returns the current item of collection being enumerated and two methods named MoveNext() and Reset().


MoveNext() moves the position to next element and returns bool indicating that is there any more elements next and will return false if no more elements are found in collection, MoveNext() needs to be called before accessing first element.


Reset() method which is pretty explanatory that it resets the enumerator and moves position back to the first element of the sequence so that it can be enumerated again.


Here is the definition of it:

public interface IEnumerator
{

   bool MoveNext();

   object Current { get; }

   void Reset();

}

 IEnumerable:

Normally Collection do not provide implementation of enumerators, instead they use IEnumerable interface for providing enumerators.

Following is the definition of IEnumerable interface:

public interface IEnumerable
{

   IEnumerator GetEnumerator();

}

Collection classes provide implementation for this interface and it just returns the specific IEnumerator instance for the collection.

 Example:

Following example will help you understand how these two interfaces work together, we will be using a String type as example as it is a framework provided type and it implements IEnumerable interface which means we can enumerate on string variables.

string enumeration = "Enumeration";
 
now as string provides implementation for IEnumerable, i can call GetEnumerator() on it to get the enumerator of string: IEnumerator enumerator = enumeration.GetEnumerator();  As we have enumerator of string available now, we can enumerate on it and print each character on screen :

while (enumerator.MoveNext()) 
{     
   char c = (char) enumerator.Current;     
   Console.Write (c); 
} 

this will output:

Enumeration


But normally when we are working we do not need to call these methods like we did above, because C# provide us foreach loop to do that more cleaner way: The above code can be written as :
 
string enumeration = "Enumeration"; 
foreach (char character in enumeration)     
   Console.Write (character); 

 IEnumerable<T> and IEnumerator<T>:

These two interfaces are almost same in implementation as IEnumerable and IEnumerator except they have generic type parameter. Here is the implementation:

public interface IEnumerator<T> : IEnumerator, IDisposable 
{    
     T Current { get; } 
} 

public interface IEnumerable<T> : IEnumerable 
{   
     IEnumerator GetEnumerator(); 
} 

The typed parameter with these interfaces provides type safety at compile time and also eliminates the overhead of boxing and unboxing of value types and they are also more convenient to the consumers of it. Arrays in c# by default implement IEnumerable<T> where T is the member type of array. Type safe implementations of IEnumerable and IEnumerator saves us from runtime errors by throwing errors at compile time if something illegal is written.

For Example:
 
void Foo (IEnumerable<int> numbers) 
{ 

}

 If i call above method by passing parameter of IEnumerable<char> it will give compile time error.

The standard practice for Collections is to expose the IEnumerable<T> and hiding the nongeneric IEnumerable using explicit interface implementation. It is because if you call GetEnumerator() directly it will return generic IEnumerator<T> which is type safe, but sometimes this rule is broken for backward compatibility scenarios as Generics were introduced after c# 2.0.

Arrays are classical example for this, as they return non generic IEnumerator to avoid breaking of  old code base which were written in c# 2.0 or older than 2.0

For getting generic IEnumerator<T> you have to explicitly cast to expose the interface.

For Example:

int[] numbers = { 1, 2, 3 }; 

var enumerator = ((IEnumerable<int> )numbers ).GetEnumerator(); 


But typically we don’t need to do this ourselves as foreach statement do this for us.



Write Code Refactoring Extensions in Visual Studio 2015


Microsoft has launched Visual Studio 2015 with many improvements and new features as well which includes simple access to online resources like Team Explorer, Salesforce, Cross platform mobile apps in C# using xamarin, cross platform html apps with Cordova, cross platform mobile apps in c# with unity, universal windows apps for any Windows 10 device, asp.net 5 in web, device preview menu bar to see UI for different screen sizes look, diagnostic features, cross platform debugging support, live code analysis and much more.

 
One of these great features also includes Extensibility templates which provide the ability to write new code refacorings, code analyzers, diagnostic and code fixations, etc. When we will add our own created code refactorings they will start to appear in the Quick Actions menu when we are working on the source code in IDE.


You will need to install Visual Studio Extensibility templates, when we install all components of VS 2015 they are automatically been installed on the machine with VS 2015.In case it was not installed you have to install it yourself first.

 
If you didn’t installed all the components of Visual Studio then you will have to install the templates by going in to Tools >> Extensions and Updates








When the popup opens go click on Online from left pane and then Search for .Net Compiler SDK:

 






 After installation restart visual studio and now you will be able to see Code Refactoring VISX template under C# >> Extensibility when creating new Project.


When you are done with installation of templates, you can find the Extensibility option in Project templates list when you go for creating new project, and on selecting extensibility you will see the templates available under it, from there select Code Refactoring (VISX) project.

 

 

Now you can create project for it, give a name to your project and click Ok. You are done with your first Code Refactoring Extension.By default the project contains a simple example extension that reverses that reverses the declaration type name.

If we right click on type declaration line we can see Quick Action in Menu, clicking on it will show the Reverse extension button and clicking it will update the class name by reversing the characters of it:



 




WCF service injection in Controller using Castle Windsor in asp.net mvc

Introduction:


In this post, we will see how we can inject WCF service dependency in the controller in asp.net mvc.

Background:

When working with web applications, normally we have persistent storage of data like Database, xml, Files , NoSQL , and we have data access in place in our controller actions to do operations on that data. Somtimes we fetch it for diaplying, saving new data, or updating existing recrods.

Nowadays service oriented applications are very common and there is trend of making service oriented applications so that we can add or remove faetures from applications easily or alter implementation without making things mess.

WCF is one of the technologies used which acts as a communication bridge between client application and persistent storage or database. We will discuss next with code sample how it is done nomally.

Ordinary Approach:

Normally, we create a WCF service project, Create our Service Contratcs in form of interfaces which tells what i take input and what i would return to callee and then others can implement those service contracts to tell how to do that. Here is an example Service Contract :

    [ServiceContract]
    public interface IUserService
    {
        [OperationContract]
        IList GetUsers();

        [OperationContract]
        User RegisterUser(User user);

        [OperationContract]
        User Login(string id,string password);

        [OperationContract]
        bool UserNameExists(string username, string email);

    }

and we then provide the implementation of contract:

    public class UserService : IUserService
    {
        private IConnectionFactory connectionFactory;

        public IList GetUsers()
        {
            connectionFactory = ConnectionHelper.GetConnection();

            var context = new DbContext(connectionFactory);

            var userRep = new UserRepository(context);

            return userRep.GetUsers();
        }

        public User RegisterUser(User user)
        {
            connectionFactory = ConnectionHelper.GetConnection();

            var context = new DbContext(connectionFactory);

            var userRep = new UserRepository(context);

            return userRep.CreateUser(user);
        }


        public User Login(string id, string password)
        {
            connectionFactory = ConnectionHelper.GetConnection();

            var context = new DbContext(connectionFactory);

            var userRep = new UserRepository(context);

            return userRep.LoginUser(id,password);
        }

        public bool UserNameExists(string username,string email)
        {
            connectionFactory = ConnectionHelper.GetConnection();

            var context = new DbContext(connectionFactory);

            var userRep = new UserRepository(context);

            var user = userRep.GetUserByUsernameOrEmail(username,email);
            return !(user != null && user.UserID > 0);

        }
    }


Now client application (in our case mvc application) would add Service Reference in the project and call the Service as shown below:

    public class AccountController : Controller
    {

        [HttpPost]
        [AllowAnonymous]
        public ActionResult SignUp(RegisterViewModel registerVM)
        {
            if (ModelState.IsValid)
            {
                UserService authenticateService = new UserService();  // this is bad design high coupling of components 

                var result = authenticateService.RegisterUser(registerVM);

                RegisterViewModel vm = result;

                return View(vm);

            }
            return View(registerVM);
        }


        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult SignIn(LoginViewModel loginVm)
        {
            if (ModelState.IsValid)
            {
                UserService authenticateService = new UserService();  // this is bad design high coupling of components

                var user = authenticateService.Login(loginVm.UserName, loginVm.Password);

                if (user == null)
                    ModelState.AddModelError("", "The user name or password provided is incorrect.");

                Session["User"] = user;

                return RedirectToAction("Index", "Home");
                
            }

            return View(loginVm);
        }
    }


What's the Problem:

If you note the above two action methods, they look fine but there is one line which is a bad design approach and voild Single Responsibility Principle and it also create high coupling between our controller and Service implementation, in future if we have to use some different implementation of IUserService , let's say new implemention which uses Entity Framework or some other Data Access Technique like MongoDB, Azure or Rest Services with JSON, we will have to change our all actions to use different class, which is not very pleasant.

Dependency Injection :

Here comes the role of dependency injection is a technique / design pattern which we will be using here. As IUserService a dependency of our Controller which is needed for the AccountController to do the job successfully.
 
As it name reflects it is used for injecting dependencies of an implementaion, there can be many dependencies or can be one only depends on the scenario, but in our this example we have one dependency of our Controller which is IUserService.
 

Castle Windsor to Help Here:

Castle Windsor is a Inversion of Control container, it can instantiate the dependencies right at the place where we need them. Dependency Injection and Inversion of Control are mostly used together, when we want dependencies to be injected, we have to use Inversion of Control as well.
 
 
For this, first of all we will have to add the library in out project from Nuget or we can download assemblies and add references to assemblies explictly. After installing the library we  can see reference to Castle.Core and Castle.Windsor in References of project:

 

 

 

Now first step is to implement the installer for CastleWindsor in which we will be telling the dependencies which will be injected by container on runtime when needed.

    public class WindsorInstaller : IWindsorInstaller
    {
        public void Install(IWindsorContainer container, IConfigurationStore store)
        {
            // registering all Controllers of the Assembly
            container.Register(Classes.FromThisAssembly()
                                .BasedOn()
                                .LifestyleTransient());

            // registeting our WcfInterceptor to intercept all WCF Service calls
            container.Register(Component
              .For()
              .ImplementedBy()
              .Named("wcf"));

            // Registering IUserService
            container.Register(Types
                .FromAssemblyContaining()
                .Where(x => x.IsInterface)
                .LifestyleTransient()
                .Configure(x =>
                { var res = x.Interceptors(InterceptorReference.ForKey("wcf")).Anywhere; }));

            // Registering implementation for IClientFactory which is dependency of WCFInterceptor implementation
            container.Register(Component
                .For()
                .ImplementedBy());

        }

 

Following is the implementation of registered dependencies above. First of all here is implementation for WcfInterceptor:

    public class WcfInterceptor : IInterceptor
    {
        public IClientFactory ClientFactory { get; set; }

        public void Intercept(IInvocation invocation)
        {
            var clientProvider = ClientFactory.GetClientProvider(invocation.Method.DeclaringType);
            try
            {
                clientProvider.Open();

                invocation.ReturnValue = CallClientProviderMethod(invocation, clientProvider);
            }
            finally
            {
                clientProvider.Close();
            }
        }

        private object CallClientProviderMethod(IInvocation invocation, IClientProvider clientProvider)
        {
            var proxy = clientProvider.GetProxy();
            return invocation.Method.Invoke(proxy, invocation.Arguments);
        }
    }

You can see the property ClientFactory of type IClientFactory which is a dependency as it is being used in Intercept method, and Intercept will get called when from client side we will exceute any method of WCF Service e.g : RegisterUser() method of SignUp action.

Here is the implementation of WcfClientFactory:

    
    public class WcfClientFactory : IClientFactory
    {
        public IClientProvider GetClientProvider(Type type)
        {
            var closedType = typeof(WcfClientProvider<>).MakeGenericType(type);
            return (IClientProvider)Activator.CreateInstance(closedType);
        }
    }
 
which just returns instance of WcfClientProvider<T>, the implementation of WcfClientprovide<T> is:
 
    public class WcfClientProvider : IClientProvider
    {
        private ChannelFactory factory;

        public WcfClientProvider()
        {
            factory = new ChannelFactory(string.Empty);
        }

        public object GetProxy()
        {
            return factory.CreateChannel();
        }

        public void Open()
        {
            if (this.factory.State != CommunicationState.Opened)
            {
                factory.Open();
            }
        }

        public void Close()
        {
            factory.Close();
        }
    }
Now we have to define Controller Factory  as well, because we have Registered IController in container we now will have to provide our own implementation of Controller Factory whose purpose is to create controller instance passing the instantiated dependencies of it.

Now the last step is to install Castle Windsor on Application start and instantiation of our Controller Facotry in Global.asax.

This is how your Global.asax code should look like:

    public class MvcApplication : System.Web.HttpApplication
    {

        private static IWindsorContainer container;

        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BootstrapContainer();
        }


        private static void BootstrapContainer()
        {
            container = new WindsorContainer()
                .Install(FromAssembly.This());
            var controllerFactory = new WindsorControllerFactory(container.Kernel);
            ControllerBuilder.Current.SetControllerFactory(controllerFactory);
        }
    }

Now we will have to change our AccountController code to add a contructor which takes IUserService instance as parameter (dependency) which will be instantiated by our Ioc Container.

Now our controller will look like :

    public class AccountController : Controller
    {
        private IUserService authenticateService;

        public AccountController(IUserService authenticateService)
        {
            this.authenticateService = authenticateService;
        }

        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult SignIn(LoginViewModel loginVm)
        {
            if (ModelState.IsValid)
            {
                var user = authenticateService.Login(loginVm.UserName, loginVm.Password);

                if (user == null)
                    ModelState.AddModelError("", "The user name or password provided is incorrect.");

                Session["User"] = user;

                return RedirectToAction("Index", "Home");
                
            }

            return View(loginVm);
        }

        [HttpPost]
        [AllowAnonymous]
        public ActionResult SignUp(RegisterViewModel registerVM)
        {
            if (ModelState.IsValid)
            {

                var result = authenticateService.RegisterUser(registerVM);

                RegisterViewModel vm = result;

                return View(vm);

            }
            return View(registerVM);
        }

Now our code is much better, it is following single responsibility principle and it is component based, we can also write Unit Tests for our actions as our all dependencies are to be provided via constructor, so unit tests are easy to write and run.



How to get First N digits of a number without Converting to String

Few days back i was asked by my senior colleague to make a method which takes two arguments as input, first the number and second the number of digits to be returned from the first argument number.

After sometime i was able to make logic of it, which was to get the number of digits of the input number and then i used that to get the number of digits using second parameter.


Here is the method:

        private static int takeNDigits(int number, int N)
        {
            int numberOfDigits = (int)Math.Floor(Math.Log10(number) + 1);

            if (numberOfDigits >= N)
                return (int)Math.Truncate((number / Math.Pow(10, numberOfDigits - N)));
            else
                return number;

        }


 and use it :

            int Result1 = takeNDigits(666, 4);
            int Result2 = takeNDigits(987654321, 5);
            int Result3 = takeNDigits(123456789, 7);
            int Result4 = takeNDigits(35445, 1);
            int Result5 = takeNDigits(666555, 6);

Output:


Result1 : 666
Result2 : 98765
Result3 : 1234567
Result4 : 3
Result5 : 666555



Custom Validation Message Helper in asp.net mvc

As i wrote earlier a post about Creating Custom Html Helpers in asp.net mvc which emphasized on how we can write custom html helper extensions in asp.net mvc according to the need, so that we can reuse them in the whole application, instead of writing plan html in View.

The example in that article was using ActionLink, today i am going to tell how we can implement custom Validation Message helper.I wanted to modify the validation message displaying in my application so that it displays * in front of required fields and the error message in tooltip of it like:





For that add a class in the project and add an extension method which will render our custom html that will be displayed for error message:

namespace CustomValidationMessageHelper.Helpers
{
    public static class Validator
    {
        public static MvcHtmlString MyValidationMessageFor<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression)
        {

            TagBuilder containerDivBuilder = new TagBuilder("div");
            containerDivBuilder.AddCssClass("tip_trigger");
            containerDivBuilder.InnerHtml = "*";


            TagBuilder midDivBuilder = new TagBuilder("div");
            midDivBuilder.AddCssClass("classic");
            midDivBuilder.AddCssClass("tip");
            midDivBuilder.InnerHtml = helper.ValidationMessageFor(expression).ToString();

            containerDivBuilder.InnerHtml += midDivBuilder.ToString(TagRenderMode.Normal);

            return MvcHtmlString.Create(containerDivBuilder.ToString(TagRenderMode.Normal));
        }
    }

}

and then define following css in a css file in my case it is site.css or you can add it in the view:

.validated {
    border-color: #DCE4EC !important;
}

textarea, input[type="text"], input[type="password"], input[type="datetime"], input[type="datetime-local"], input[type="date"], input[type="month"], input[type="time"], input[type="week"], input[type="number"], input[type="email"], input[type="url"], input[type="search"], input[type="tel"], input[type="color"], .uneditable-input {
    padding: 3px 3px;
    border: 1px solid #DCE4EC;
}


        
.tip {
    background: none repeat scroll 0 0 #FFFFFF;
    border: 1px solid #808080;
    border-radius: 10px;
    box-shadow: 0 1px 10px rgba(32, 32, 32, 0.5);
    color: red;
    display: none;
    font-size: 12px;
    font-style: normal;
    margin-left: 10px;
    margin-top: -24px;
    padding: 4px;
    position: absolute;
    z-index: 999999;
}

.tip_trigger {
    width: 10px;
    float: right;
    color: red;
    margin-left: 3px;
}

Now we have to add client side code, which i have written in jquery in a js file or directly in view, in my case i have it in CustomValidation.js file:

$(document).ready(function () {
    //Tooltips
    var tip;
    $(".tip_trigger").hover(function () {
        console.log("hovered");
        tip = $(this).find('.tip');
        console.log($(this).find('.tip').find('span').html())
        if ($(this).find('.tip').find('span').html() != '') {
            $(this).find('.tip').show(); //Show tooltip
        }
    }, function () {
        $(this).find('.tip').hide(); //Hide tooltip 

    });

    ////Required fields
    $('input').each(function () {
        var req = $(this).attr('data-val-required');
        if (undefined != req) {
            $(this).css("border-color", "#DA9BA2")

        }
        if ($(this).val() != '') {

            $(this).addClass("validated");

        }

    });

    $('input').blur(function () {

        if ($(this).val() != '') {

            $(this).addClass("validated");
        }
        else {

            $(this).css("border-color", "#DA9BA2")
        }

    });


});


Now in the View add the reference to the related js and css files in the head section of View:

    <link href="@Url.Content("~/Content/site.css")" rel="stylesheet"/>
    <script src="@Url.Content("~/Scripts/jquery-1.9.1.js")"></script>
    <script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")"></script>
    <script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/CustomValidation.js")" type="text/javascript"></script>


Now in your view add using statement of the namespace and now you can access the Helper method in the View:

@model CustomValidationMessageHelper.ViewModels.SignUpViewModel
@using CustomValidationMessageHelper.Helpers
@{
    Layout = null;
}


@Html.TextBoxFor(model => model.FirstName, new { @class = "form-control input-sm" })
@Html.MyValidationMessageFor(model => model.FirstName)

The sample project can be  downloaded from here



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


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 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.



How to Convert DataTable to List in C#

When writing Data Access Layer, when we get data from the database using ADO.net, most of the times we use DataTable or DataSet to hold the data in memory, then we have to map the DataTable  to List of Model type.


One way is to iterate on the rows of DataTable and create objects of Model and add to List one. Let me show you with example.


I have table in database which has information about Doctors, my table name is Doctor which contains different columns which are for capturing information of Doctor.


I have following Model class on front end which represents Doctor :

public class Doctor
{
    public int ID { get; set; }
    public string Name { get; set; }
    public string ImagePath { get; set; }
    public string Type { get; set; }
}



When we will get Doctors from database in datatable we can create a list of Doctors with following approach in our Data Access:

List doctors = new List();
for (int i = 0; i < dtDoctors.Rows.Count; i++)
{

    Doctor objDoctor = new Doctor();

    objDoctor.ID = dtDoctors.Rows[i]["DoctorID"].ToString();
    objDoctor.Name = dtDoctors.Rows[i]["Name"].ToString();
    objDoctor.ImagePath = dtDoctors.Rows[i]["Image"].ToString();
    objDoctor.Type = dtDoctors.Rows[i]["Type"].ToString();

    doctorList.Add(objDoctor);
}

It will surely do the job for you, but think that you have many tables in your database and whenever you will fetch data you will have to do a loop the way i showed above and will have to map properties from datatable, which does not look cool as we are rewriting same thing again and again which is against DRY principle.


We can achieve what we have did above using generics,relection and extension methods feature provided by .Net Framework.We can add the following  extension method in our project and just call it to convert DataTable to List of Type which we want to.

Following is the extension method for it:

public static class ExtensionMethods
{
    public static List ToList(this DataTable dt)
    {
        List data = new List();
        foreach (DataRow row in dt.Rows)
        {
            T item = GetItem(row);
            data.Add(item);
        }
        return data;
    }

    private static T GetItem(DataRow dr)
    {
        Type temp = typeof(T);
        T obj = Activator.CreateInstance();

        foreach (DataColumn column in dr.Table.Columns)
        {
            foreach (PropertyInfo pro in temp.GetProperties())
            {
                if (pro.Name == column.ColumnName && dr[column.ColumnName] != DBNull.Value)
                    pro.SetValue(obj, dr[column.ColumnName], null);
                else
                    continue;
            }
        }
        return obj;
    }
}

Now we can call it on instance of DataTable and can specify that convert it to which type of List.

For Example:

List doctors = dtDoctors.ToList();


Now that looks cool, we have just written two extension method for DataTable and now we can reuse it anywhere which enables us to reduce code redundancy.


One thing to consider is that the column names you are returning from your sql query or Stored Procedure should be same as of the properties in the Model class and the datatype should also be matched so that i can be converted.