Showing posts with label c#. Show all posts
Showing posts with label c#. Show all posts

Thursday, 20 March 2014

Reference Types and Value Types

Reference Types:

variables store reference to a type.

we will see some scenarios :
scenario1:
        class student
        {
            public int id { get;set;}

        }
//'s1' is a variable of type 'student'
student s1 = new student();
//Assign value of s1 to s2 .(value of s1 is address of student object)
student s2 = s1;
s1.id = 23;
// since s1 and s2 are referring same student object, s1.id and s2.id contains same value.
Console.WriteLine("s1 " + s1.id + "  s2 " + s2.id ); 
o/p : s1 23  s2 23

scenario2:

//'s1' is a variable of type 'student'
student s1 = new student();
//Assign value of s1 to s2 .(value of s1 is address of student object)
student s2 = s1;
s1.id = 34;
//creating second instance of student object.
        s1 = new student();
        s1.id = 23;
// s2 is still referring to old student object, but s1 is now referring new student object, hence s1        and s2 holds 
different values
Console.WriteLine("s1 " + s1.id + "  s2 " + s2.id ); 
o/p : s1 23 s2 34

Value Types:

Variables holds value.
int x1 = 10;
//Assign value of x1 to x2(value of x1 is 4 not the address of 4)
int x2 = x1;
x1 = 23;
// since x2 holds value of x1, even if we initialize x1 value to 23 the value of x2 does not change to 23.
Console.WriteLine(x2);
o/p: 10

Wednesday, 19 March 2014

Sample code which uses Delegates and Without using Delegates

You can think of a delegate type as being a bit like an interface with a single method. It specifies the 
signature of a method, and when you have a delegate instance, you can make a call to it as if it were a
method with the same signature. Delegates provide other features, but the ability to make calls with a
particular signature is the reason for the existence of the delegate concept.

we will see the implementation of calculating two numbers (Addition and Multiplication) using delegates and with out using delegates.


without using Delegate:


without using delegates, we need to create interface and implement that interface in two classes. after that we have to create objects for them and access them using object.methodname.


here is the code for it:

-------------------------------------------------------
namespace WithAndWithoutDelagates
{
    interface calculate1
    {
        int Eval(int a, int b);
       
    }
    class Add:calculate1
    {
        int calculate1.Eval(int a, int b)
        {
            return a + b;
        }
    }

    class Multiply : calculate1

    {
        int calculate1.Eval(int a, int b)
        {
            return a * b;
        }
    }
}

//////////////////////////////////////////////////////////////////////////////

 class Program
    {
static void Main(string[] args)
        {
           Console.WriteLine(DoWork1(new Multiply()));

            Console.WriteLine(DoWork1(new Add()));

            Console.ReadLine();
        }

        static int DoWork1(calculate1 f)

        {
            return f.Eval(20, 30);
         
        }
}

///////////////////////////////////////////////////////////////////////////

using delegates:

No interfaces, no clunky .eval stuff, no object instantiation, just simple function-pointer like usage, for a simple task.

-------------------------------------------------
 class Program
    {
        public delegate int calculate(int x, int y);

        static void Main(string[] args)

        {
            calculate del1 = new calculate(Add);
            calculate del2 = new calculate(Multiply);

   Console.WriteLine(DoWork(del1));

            Console.WriteLine(DoWork(del2));
            Console.ReadLine();
        }

        static int Add(int x, int y) 

        {
            return x+y;
        }

        static int Multiply(int x, int y)

        {
            return x*y;
        }

        static int DoWork(calculate f)

        {           
            var res = f(20, 30);
            return res;
        }

    }

Thursday, 25 April 2013

Func delegate


The Func and Action delegates are a set of generic delegates that can work for methods of any return type
(for Func) and reasonable number of arguments. These delegates are defined in the System namespace. The
Action represents any function that may accept up to 16 parameters and returns void, for example,
Action<T1>, where T1 refers to the input parameters and can be of any data type. Func is the same as Action
but it has a return value of any type, for example, Func<T1, TResult> where T1 input parameters can be of

any type and TResult is a returned value of any type. The only difference between Action and Func is the
return value. In the following sections, we will explore more about Func


Func

The Func class is used to encapsulate method information in C#. The Func class is defined in the mscorlib.
dll (C:\Windows\Microsoft.NET\ Framework\v4.0.30319),



The signature of the Func<TResult> class is shown in Listing 1-1

Listing 1-1. Signature of the Func<TResult>

.class public auto ansi sealed Func<+ TResult> extends System.MulticastDelegate

The Func class declaration is shown in Listing 1-2.
Listing 1-2. Func Class Definition in IL Format
.class public auto ansi sealed Func<+ TResult> extends System.MulticastDelegate
{
.method public hidebysig specialname rtspecialname instance void
.ctor(object 'object', native int 'method') runtime managed
{}
.method public hidebysig newslot virtual instance class System.IAsyncResult
BeginInvoke(class System.AsyncCallback callback, object 'object') runtime managed
{}
.method public hidebysig newslot virtual instance !TResult
EndInvoke(class System.IAsyncResult result) runtime managed
{}
.method public hidebysig newslot virtual instance !TResult

Invoke() runtime managed

{}
}

Func<TResult> is a generic type, which inherits from the MulticastDelegate class and later inherits
from the delegate class.

 Func and Delegate relationship
The Func<TResult> class will have all the functionality and properties of the MulticastDelegate and
Delegate types due to the inherent relationship between Func<TResult> and MulticastDelegate and the
Delegate classes. The Func class has BeginInvoke, EndInvoke, and Invoke as well as the constructor method.

 An Example of Func<TResult> Type

class Program
{
static void Main(string[] args)
{
ExampleOfFunc exampleOfFunc = new ExampleOfFunc();
Console.WriteLine("{0}", exampleOfFunc.Addition(exampleOfFunc.Add));
Console.WriteLine("{0}", exampleOfFunc.Addition(
() =>
{
return 100 + 100;
}));
}
}
public class ExampleOfFunc
{
public int Addition(Func<int> additionImplementor)
{
if (additionImplementor != null)
return additionImplementor();
return default(int);
}
public int Add()
{
return 1 + 1;
}
}

This program will produce the following output:
2
200

Cheers!!
Mani Kumar Yegateeli



Wednesday, 24 April 2013

Extension Methods


In .NET, extension methods provide a mechanism by which you can add functionality to a type without
modifying it to avoid the risk of breaking code in existing applications. You can also add additional
methods in the interface without altering the existing class libraries.
So the extension method allows you to extend the existing compiled types to have a new functionality
without needing to directly update the type. It is quite helpful when you need to inject new functionality
into types where you do not have an existing code base. It can also be useful when you need a class to
support a set of members, but it cannot modify the original type declaration. Using the extension method,
you can add functionality to compiled types while providing the illusion that these methods were there all
along.
To extend a type’s functionality using the extension method technique provided by the C#, you need
to do the following:
• Make a static class.
• Add a static method in this static class with the appropriate functionality. In the
parameter list of this new method, add an extra parameter this along with the type
name for which this method will extend the functionality. For example,
GetLastCharacter method in below extends functionality for the string type.

an extension method is defined for the string type. This extension method is used to
determine the last character of a word whose type is string.

 An Example of the Extension Method :

using System;
namespace ExtensionMethod
{
class Program
{
static void Main(string[] args)
{
string data = "abcd";
Console.WriteLine("{0}", data.GetLastCharacter()); /* Calls extension defined for
the string type. */
}
}
public static class ExtensionMethods /* A Static class defined */
{
public static string GetLastCharacter(this string data)
/* A static method with the parameter
* this along with the type name string */
{
if (data == null || data == string.Empty)
return string.Empty;
return data[data.Length - 1].ToString();
}
public static Int32 GetNum(this Int32 dd)
{
return dd;
}
}
}

The program will produce the following output:
d


The GetLastCharacter extension method determines the last character from the input data if the data
are not null or do not contain an empty value. In above code, a static class ExtensionMethods is
defined and a static method GetLastCharacter is added. The first parameter contains the this keyword
along with a parameter of the type that is going to be extended, in this case it is string.
When you define any extension method for a type, it shows Visual Studio’s IntelliSense along with the
standard methods of that type.

Cheers,
Mani Kumar Yegateeli