Saturday, 28 May 2016

value type

When we create variable using data types as int, bool, struct, enumeration this all target to direct value.

The value type consist two main categories:
  1. Struct
  2. Enumeration

Struct has following categories:
  1. Integer types
  2. floating point types
  3. decimal
  4. bool
  5. User defined struct
This all are stored value into heap memory.
A value type cannot contain null value but the null-able type does allow value type to be a null.
Each value type has an implicit default constructor that initializes the default value of that type.

Value type
Default value
false
0
'\0'
0.0M
0.0D
The value produced by the expression (E)0, where E is the enum identifier.
0.0F
0
0L
0
0
The value produced by setting all value-type fields to their default values and all reference-type fields to null.
0
0
0


you can also visit:  www.mybook-lang.com

lambda

A Lambda expression is an anonymous function that enables you to create delegates or expression tree types.
By using lambda expression, you can write local function that can be passed as arguments or returned as the value of function calls.
It is very useful in place where a method is being used only once and the method definition is short.
It saves time to declaring and writing a separate method.
Syntax:
(input parameters) => expression
Lambda Expression:
The operation “=>” is called lambda operator. You can read as “goes to”.
Lambda express has left and right side.
x => x*x
So, here you can see x goes to x*x. where left side x is input parameter x*x is the code execution block.

Example:

using System;

class Program
{
    delegate int del(int x, int y);
    
    static void Main()
    {
        del myFunct = (x, y) => x * y;

        int result1 = myFunct(2, 3);
        Console.WriteLine("Using Delegate: {0}", result1.ToString());
    }
}
Output:
Using Delegate: 6
Press any key to continue…

In above example we have create delegate using delegate keyword with two parameters x and y.
Now this delegate passed x and y value and get result as integer and display it to console screen.
Let’s take an example and compare with class:

using System;

class Program
{
    delegate int del(int x, int y);
    
    static class myClass
    {
        public static int del(int x, int y)
        {
            return x * y;
        }
    }

    static void Main()
    {
        del myFunct = (x,y) => x*y;
        
        int result1 = myFunct(2,3);
        Console.WriteLine("Using Delegate: {0}", result1.ToString());

        int result2 = myClass.del(2, 3);
        Console.WriteLine("Using Class: {0}", result2.ToString());
    }
}
Output:
Using Delegate: 6
Using Class: 6
In above example you can see that we have created delegate and static class. Class has static int del method which returns multiplication of x and y.
Different between lambda expression and using class you can see we have return much lines to get result as same lambda expression gives.
So if your code of line is short then you can use lambda expression to get result with single line.
A statement lambda resembles an expression lambda except that the statement(s) is enclosed in braces.
(input parameters) => { statement block };
You can write number of statement to the statement block but typically more than two is good practice.
Statement lambda is like a anonymous methods and which cannot be used to create expression trees.

Let’s take an example of Statement Lambda:

using System;

class Program
{
    delegate void del(int x, int y);
   

    static void Main()
    {
        del myFunct = (x, y) => { 
            string s = "Multiplication of X and Y is: " + x * y; 
            Console.WriteLine(s); 
        };
        
        myFunct(2,3);

    }
}
Output:
Multiplication of X and Y is: 6
Press any key to continue…
Using Func delegates are very useful for encapsulating user defined expression that is applied to each element in a set of source data.
Example:

using System;

class Program
{
    delegate TResult Func<TArg0, TResult>(TArg0 arg0);

    delegate bool Func(int x);

    static void Main()
    {
       
        Func<int, bool> myf = x => x == 5;
        bool result = myf(4);

        Console.WriteLine("Result: {0}", result);


        Func<int, int> myf1 = x => x * 5;
        int result2 = myf1(4);

        Console.WriteLine("Result: {0}", result2);

        
    }
}
Output:
Result: False
Result: 20
Press any key to continue...

In above example you can see that we have crated Func<TArg0, TResult> delegate. It takes TArge0 as argument and TResult as parameter.

Standard Query Operation Methods:

using System;
using System.Linq;

class Program
{
    static void Main()
    {
        int[] numbers = { 4, 1, 5, 5, 8, 7, 9, 10 };
        int odd = numbers.Count(r => r % 2 != 0);

        Console.WriteLine("Odd Number: {0}", odd);

    }
}
Output:
Odd Number: 5

Notes:
Lambda expression should be short.
Lambda expression is useful with LINQ.
you can also visit:  www.mybook-lang.com

void

It specifies a return value type for a method that doesn’t have return value.
Void is structure type.

public void SampleMethod()
{
    // Body of the method.
}

void is an alias for the .NET Framework System.Void type. 
void is also used in an unsafe context to declare a pointer to an unknown type.

you can also visit:  www.mybook-lang.com

set

Encapsulation allows us to secure date source and data set to external worlds.
It is used to set data to the variable.
You can verify, validate, and check authorization data before store into the data source.
Syntax:

class myClass
{
    private string _name;

    public string Name
    {
        set
        {
            if (!string.IsNullOrWhiteSpace(value))
            {
                _name = value;
            }
            else
            {
                throw new Exception("Invalid string.");
            }
        }
    }
}
Let's take an example and validate property before assign to private field:

using System;

class Program
{
    static void Main()
    {
        myClass cls = new myClass();
        cls.Name = "1Sample";

        cls.print();
    }
}

class myClass
{
    private string _name;

    public string Name
    {
        set
        {
            if (VerifyString(value))
            {
                _name = value;
            }
            else
            {
                throw new Exception("Invalid string.");
            }
        }
    }

    public bool VerifyString(string str)
    {
        int i=0;
        foreach(char c in str.ToCharArray())
        {
            if(int.TryParse(c.ToString(),out i))
            {
                return false;
            }
        }
        return true;
    }

    public void print()
    {
        if(this._name!=null)
        {
            Console.WriteLine("Name: {0}", this._name);
        }
        else
        {
            Console.WriteLine("Provide a valid string");
        }
    }
}

Output:
Provide a valid string
Press any key to continue…
In above setter example you have seen that before assign value to the private property of myClass verify method verify string if string contain any digits. If string has any digits then it is not assign any value and if it has not any digits it will show string value which is assign.
If you provide only get method to the property then it will be a read only property.
If you provide only set method to the property then it will be a write only property.
Read more about types of property. class properties

you can also visit:  www.mybook-lang.com

get

Encapsulation allows us to secure date source and data set to external worlds.
Getter:
It is used to get data from variable.
You can modify the represent of the data like uppercase, lowercase or if date time change the date formats.
You can check permission before providing date back to the caller.
Syntax:

class myClass
{
    private string _name;

    public string Name
    {
        get
        {
            return _name;
        }
    }
}
Let' ake an example of getter method to modify enter string before get;

using System;

class Program
{
    static void Main()
    {
        myClass cls = new myClass();
        
        Console.WriteLine("Name: {0}", cls.Name);
    }
}

class myClass
{
    private string _name = "Sample";

    public string Name
    {
        get
        {
            return "Mr." + _name;
        }
    }
}
Output:
Mr. Sample
Press any key to continue…
If you provide only get method to the property then it will be a read only property.
If you provide only set method to the property then it will be a write only property.
Read more about types of property. class properties

you can also visit:  www.mybook-lang.com

binarywriter

Create binary file.
It’s used to write primitive data in binary format.
You can use parameter constructor of binary writer to create binary file.
List of parameter constructor in Binary Writer:
Namespace required to use binarywriter is System.IO


public BinaryWriter(Stream output);
Stream: output is the name of the output stream.

public BinaryWriter(Stream output, Encoding encoding);
Encoding: is the character encoding to use. Encoding is available in System.Text namespace.  Encoding is an abstract class. It is used to various text formats.

public BinaryWriter(Stream output, Encoding encoding, bool leaveOpen);
leaveOpen: True to leave the stream open after the BinaryReader object is disposed; otherwise, false.
Let’s take an example of BinaryWriter:

using System;
using System.IO;
using System.Text;

class Program
{
    static void Main()
    {
        try
        {
            int[] intArray = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

            using(BinaryWriter bw = new BinaryWriter(File.Open("test.txt",FileMode.OpenOrCreate)))
            {
                foreach(int a in intArray)
                {
                    bw.Write(a);
                }
            }
        }
        catch(Exception ex)
        {
            Console.WriteLine(ex.Message.ToString());
        }
    }
}
Now you can check file “test.txt” in bin directory of the program.
In this file binary data stored. If you want to read those data from original format you can use BinaryReader.

List of methods in BinaryWriter:
Write: Uint64, Uint32, Uint16, string, single, sByte, Int64, Int32, Int16, Double, Decimal, Char[], char, Byte, Byte[], Boolean to write in binary file with respective datatypes.
Dispose: release all resource used by the current instance of binarywriter.
Close: close the current reader and underlying stream.
Seek: Set the position within the current stream.
Flush: Clear all buffers for the current writer and causes any buffered data to be written to underlying device.
Finalize: Allows an object to try to free resource and perform other cleanup operation before it is reclaimed by garbage collection.


you can also visit:  www.mybook-lang.com

binaryreader

Read binary file.
It is used to read primitive data types as binary values in a specific encoding.
It does not contain default constructor but you can use parameter constructor.
List of parameter constructor:

public BinaryReader(Stream input);
Initializes a new instance of the BinaryReader class based on the specified stream and using UTF-8 encoding.
Stream: input is name of the input stream.

public BinaryReader(Stream input, Encoding encoding);
Initializes a new instance of the BinaryReader class based on the specified stream and character encoding.
Encoding: is the character encoding to use. Encoding is available in System.Text namespace.  Encoding is an abstract class. It is used to various text formats.

public BinaryReader(Stream input, Encoding encoding, bool leaveOpen);
Initializes a new instance of the BinaryReader class based on the specified stream and character encoding, and optionally leaves the stream.
leaveOpen: True to leave the stream open after the BinaryReader object is disposed; otherwise, false.
Take an example of binary reader:

using System;
using System.IO;
using System.Text;

class Program
{
    static void Main()
    {
        try
        {
            using (BinaryReader br = new BinaryReader(File.Open("test.txt", FileMode.Open)))
            {
                int position = 0;

                int length = (int)br.BaseStream.Length;

                while (position < length)
                {
                    int a = br.ReadInt32();
                    Console.WriteLine(a);
                    position += sizeof(int);
                }
            }
        }
        catch(Exception ex)
        {
            Console.WriteLine(ex.Message.ToString());
        }
    }
}
In above example using binary reader open “test.txt” file which is created by binary writer and then one by one read binary stream from test file and added console.
Sizeof(int) use for jump to the next position. Here we used int and int sizeof is 4.
List of methods in BinaryReader:
Read: Reads character from the underlying stream. You can also use Byte[], Char[], Int32;
ReadUInt64: Reads an 8 byte unsigned integer from the current underlying stream.
ReadUInt32: Reads a 4 byte unsigned integer from the current underlying stream.
ReadUInt16: Reads a 2 byte unsigned integer from the current underlying stream.
ReadString: Reads a string from the current underlying stream.
ReadSingle: Reads a a 4 byte floating point value from the current underlying stream.
ReadSByte: Reads a signed byte from the current underlying stream.
ReadInt32: Reads a 4 byte signed integer from the current underlying stream.
ReadInt16: Reads a 2 byte signed integer from the current underlying stream.
ReadDobule: Reads a 8 byte floating point value from the current underlying stream.
ReadDecimal: Reads a decimal value from the current underlying stream.
ReadChar: Reads the next character from the current stream and advaces the current position of the stream.
ReadChars(int32): Reads the specified number of character from the current stream.
ReadByte: Read the next byte from the current stream and advance the current position of the stream.
ReadBytes(int32): Reads the specified number of bytes from the current stream into a byte array.
ReadBoolean: Read a Boolean value from the current underlying stream.
Read7BitEncodedInt: Reads in a 32 bit integer in compressed format.
Close: Close the current reader and the underlying stream.
Dispose: Release all resource used by the current instance of the binary reader class.
Finalize: Allows an object to try to free resources and perform other cleanup operations before it is reclaimed garbage collection.
PeekChar: Return the next available character and does not advance the byte or character position.

you can also visit:  www.mybook-lang.com