Different ways of doing serialization and deserialization in .Net (Asp.net/Asp.net MVC) (Part 3)


Method 1: Using System.Runtime.Serialization.Json Namespace

Method 2: Using System.Web.Script.Serialization Namespace

Method 3:

In this method we will use the Newtonsoft.Json dll

This is one of the most popular open source dll, we install it from Nuget package manager or from google download it and add to our project

We can write code as given below


using Newtonsoft.Json;
using System;

namespace WebApplication1
{
    public partial class Demo3 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            EmpDemo objEmp = new EmpDemo
            {
                Id = 1021,
                EmpName = "Chandradev",
                EmpAddress = "Bangalore"
            };

            string jsonData = JsonConvert.SerializeObject(objEmp);
            Response.Write("<b>Converting to Json </b> " + "</br>");
            Response.Write("</br>");
            Response.Write(jsonData);
            Response.Write("</br>");

            var objEmp1 = JsonConvert.DeserializeObject<EmpDemo>(jsonData);
            Response.Write("</br>");
            Response.Write("Converting Json to .Net Object:");
            Response.Write("</br>");
            Response.Write("Id: " + objEmp1.Id + "</br>");
            Response.Write("EmpName: " + objEmp1.EmpName + "</br>");
            Response.Write("EmpAddress: " + objEmp1.EmpAddress + "</br>");
        }

        public class EmpDemo
        {
            public int Id { get; set; }
            public string EmpName { get; set; }
            public string EmpAddress { get; set; }
        }
    }
}

Note: donot forget to include the Newtonsoft.Json namespace in your code. This approach can be used in Asp.net or asp.net mvc application.

Different ways of doing serialization and deserialization in .Net (Asp.net/Asp.net MVC)(Part 2)


different-ways-of-doing-serialization-and-deserialization-in-net-asp-netasp-net-mvc (Part 1)

Method 2 approach

we will use System.Web.Script.Serialization namespace of .net framework

Step 1: Create the EmpDemo Class and write the code in code behind file like given below


using System;
using System.Web.Script.Serialization;

namespace WebApplication1
{
    public partial class Demo1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            EmpDemo objEmp = new EmpDemo
            {
                Id = 1021,
                EmpName = "Chandradev",
                EmpAddress = "Bangalore"
            };

            JavaScriptSerializer js = new JavaScriptSerializer();

            Response.Write("<b>Converting to Json </b> " + "</br>");
            Response.Write("</br>");
            string jsonData = js.Serialize(objEmp);
            Response.Write(jsonData);
            Response.Write("</br>");

            var objEmp1 = js.Deserialize(jsonData);
            Response.Write("</br>");
            Response.Write("<b> Converting Json to .Net Object: </b>");
            Response.Write("</br>");
            Response.Write("Id: " + objEmp1.Id + "</br>");
            Response.Write("EmpName: " + objEmp1.EmpName + "</br>");
            Response.Write("EmpAddress: " + objEmp1.EmpAddress + "</br>");
        }
    }

    public class EmpDemo
    {
        public int Id { get; set; }
        public string EmpName { get; set; }
        public string EmpAddress { get; set; }
    }
}

Summary: This approach will be suitable in asp.net or asp.net mvc application.

What are the difference between Object, Var and dynamic keyword in C# ?


When I was giving the interview I was getting this question in all interview. So I am sharing this short answer for everyone.

This all keywords looks like used for same purpose and there are some differences in each one.

What is the use of this Keyword in C# ?


This keyword is used to refer the current instance of class. It is also used as modifier of the first parameter of an extension method.

The following are the common use of this Keyword
1. To qualify the member hidden by similar name.
2. To pass object as parameter to other methods

Let see one simple example for this

using System;

namespace This_Keyword_Example
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create object
            Employee objEmp = new Employee("Chandradev","Prasad");
            //Display result
            objEmp.printEmployee();
            Console.ReadKey();
        }
    }
    class Tax
    {
       public static decimal CalcTax(Employee E)
        {
            return 0.08m * E.Salary;
        }
    }
    class Employee
    {
        private string firstName;
        private string lastName;
        private decimal salary = 5000m;
        public  Employee(string firstName,string lastName)
        {
            this.firstName = firstName;
            this.lastName = lastName;
        }   

        public void printEmployee()
        {
            Console.WriteLine("FirstName: {0}\nLastName: {1}",firstName,lastName);
            Console.WriteLine("Taxes: {0:C}",Tax.CalcTax(this));
        }
        public decimal Salary
        {
            get { return salary; }
        }

    }
}

This_Keyword
Explanation:

In the above example, this.name and this.alias is representing the private string value of Employee class
And in Tax.calcTax(this) , we are passing the class objet of Employee as parameter to other CalcTax method of Tax class.

Let see one more simple example of this Keyword

using System;

namespace This_Keyword
{
    class Program
    {
        static void Main(string[] args)
        {
            Test obj = new Test();
            obj.Get();
        }
    }
    class Test
    {
        int a=10,b=20;
        public void Get()
        {
            int a = 30, b = 40;
            Console.WriteLine("The class variable are a={0},b={0}", this.a, this.b);
            Console.WriteLine("The Local Variable are a={0},b={0}",a,b);
            Console.ReadLine();
        }

    }
}

This1
Explanation:

In the above example we are differentiating the class variable i.e. global variable and local variable when both the variable names are same. If we will use the this keyword then it will show only class variable i.e. Global variable.

There are several usages of this keyword in C#.

1. To qualify members hidden by similar name
2. To have an object pass itself as a parameter to other methods
3. To have an object return itself from a method
4. To declare indexers
5. To declare extension methods
6. To pass parameters between constructors
7. To internally reassign value type (struct) value.
8. To invoke an extension method on the current instance
9. To cast itself to another type
10. To chain constructors defined in the same class

Named and optional Parameter in C#


Named and optional parameters are the one of the new features of C# 4.0. This feature allows developers to have an option to create named and optional parameters in a method.

Named Parameter

Now let see the example of Named Parameter:

NamedParameter

Complete C# code

using System;

namespace Named_OptionalParameter
{
    class Program
    {
        static void Main(string[] args)
        {
            var objPrice = new PriceClass();
            //Traditional approach to Call the method
            Console.WriteLine(objPrice.CalculatePrice(10,100,false));
            // Using Named parameter approach to call the method
            Console.WriteLine(objPrice.CalculatePrice(EliteMember:false,quantity:10,price:100));
            Console.ReadLine();
        }
    }
    public class PriceClass
    {
        public double CalculatePrice(int quantity,double price, bool EliteMember)
        {
            if (EliteMember)
            {
                return quantity * price - 10;
            }
            else
                return quantity * price;
        }
    }
}

In the above code we saw that we have created the method to calculate price and we are passing the parameter as int, double, bool as parameter. But if we will not pass in this order it will through the exception upto C# 3.0. But from C# 4.0 there is not mandatory to pass parameter as same as method defined.

We can pass parameter as per as developer desire like this
// Using Named parameter approach to call the method

Console.WriteLine(objPrice.CalculatePrice(EliteMember:false,quantity:10,price:100));

Optional Parameter

Now let see the example of Optional parameter example

OptionalParameter

If you will see in the above example, CalculatePrice Method has two parameter i.e price and eliteMember. For that parameter it is not mandatory to pass the parameter. If we will not pass the parameter then it will take default value which one we have defined in parameter.

For example, if we have to override the optional value of method then this also possible, we have to just pass the desire value in parameter as shown in above image.

Summary:

We learned that what is the named and optional parameter in C#

Extension Method in C#


Extension method is the one of the cool features came in C# 3.0. As the name suggest, it extends the functionality of method in very simple way.

For example, we are going to use some dll method and we don’t have access to inherit or override the class. But our requirement is there to extend the method with some extra functionality. Then extension method will very handy to use in this scenario.

Let’s see one extremely simple example

Extension_Method

Complete code in C#

using System.Collections.Generic;
 
namespace ExtensionMethod
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            EmpElite objee = new EmpElite();
            objee.AllEliteEmps(); //This will contains Ram, Mohan,Hari
            objee.NewEliteEmps(); //This will contains John,James,Suresh
        }
    }
 
    public class EmpElite
    {
        public List<string> AllEliteEmps()
        {
            return new List<string> { "Ram", "Mohan", "Hari" };
        }
    }
 
    public static class ExtendedEmpElite
    {
        public static List<string> NewEliteEmps(this EmpElite elite)
        {
            return new List<string>() { "John", "James", "Suresh" };
        }
    }
}

Note:
In the above example, we saw that there is one EmpElite Class with AllEliteEmps method, Which contains the list of elite Emps. We have extended the AllEliteEmps method with NewEliteEmps using static Keyword and this Keyword. We have also passed the Class name and instance name which one we are going to extend.

Now whenever we will call this method i.e. ExtendedEmpElite then we will get the expected output.

Point to remember:
• An extension method must be defined in a top-level static class.
• An extension method with the same name and signature as an instance method will not be called.
• Extension methods cannot be used to override existing methods.
• The concept of extension methods cannot be applied to fields, properties or events.

What is the attribute in C# ?


Attribute is the piece of information which is generally used to pass message to developer whenever he/she is going to use that class, method or properties in his application.

Suppose you have created some .dll or Framework which one you have exposed to developer. Now you have written some new method with new features. Now you want to inform to developers that “please use the new method for better performance”. Then you can take help of attribute in C#.

attribute

Generally we will get this message in .net F/w if you will use some old method which is currently no more in use.

For using the attribute we can use Obsolete keyword and pass the required message to developer as per as given below code.

Attribute1

Note: If we have to completely restrict the end user to use that method in his application then you can pass true in obsolete method as given below images

Attribute2

Now end user developer cannot use the “CalculateAmt” method in his application.

Summary

In the above demo, we saw that how to use attribute in C#. It is very handy process to pass message to developer if you are going remove the old method.