Monday, February 8, 2016

Ref Vs Out Keywords in C#

Ref and out parameters are used to pass an argument within a method. In this article, you will learn the differences between these two parameters. Ref and out change the behavior of method parameters. Sometimes we want the actual value of a variable to be copied as the parameter. Other times we want a reference. These modifiers affect definite assignment analysis.



Ref
The ref keyword is used to pass an argument as a reference. This means that when value of that parameter is changed in the method, it gets reflected in the calling method. An argument that is passed using a ref keyword must be initialized in the calling method before it is passed to the called method.

Out
The out keyword is also used to pass an argument like ref keyword, but the argument can be passed without assigning any value to it. An argument that is passed using an out keyword must be initialized in the called method before it returns back to calling method.

Example using ref and out:

using System;

class Program
{
    static void Main()
    {
 string value1 = "cat"; // Assign string value
 SetString1(ref value1); // Pass as reference parameter
 Console.WriteLine(value1); // Write result

 string value2; // Unassigned string
 SetString2(1, out value2); // Pass as out parameter
 Console.WriteLine(value2); // Write result
    }

    static void SetString1(ref string value)
    {
 if (value == "cat") // Test parameter value
 {
     Console.WriteLine("Is cat");
 }
 value = "dog"; // Assign parameter to new value
    }

    static void SetString2(int number, out string value)
    {
 if (number == 1) // Check int parameter
 {
     value = "one"; // Assign out parameter
 }
 else
 {
     value = "carrot"; // Assign out parameter
 }
    }
}

Output:
Is cat
dog
one 

Ref and out in method overloading
Both ref and out cannot be used in method overloading simultaneously. However, ref and out are treated differently at run-time but they are treated same at compile time (CLR doesn't differentiates between the two while it created IL for ref and out). Hence methods cannot be overloaded when one method takes a ref parameter and other method takes an out parameter. The following two methods are identical in terms of compilation.

class MyClass
{
 public void Method(out int a) // compiler error “cannot define overloaded”
 {
 // method that differ only on ref and out"
 }
 public void Method(ref int a) 
 {
 // method that differ only on ref and out" 
 }
}

However, method overloading can be done, if one method takes a ref or out argument and the other method takes simple argument. The following example is perfectly valid to be overloaded.

class MyClass
{
 public void Method(int a) 
 {
 
 }
 public void Method(out int a)
 {
 // method differ in signature.
 }
}

Note:
The out and ref keywords are useful when we want to return a value in the same variables as are passed as an argument.

Ref Vs Out


Ref
Out
The parameter or argument must be initialized first before it is passed to ref.
It is not compulsory to initialize a parameter or argument before it is passed to an out.
It is not required to assign or initialize the value of a parameter (which is passed by ref) before returning to the calling method.
A called method is required to assign or initialize a value of a parameter (which is passed to an out) before returning to the calling method.
Passing a parameter value by Ref is useful when the called method is also needed to modify the pass parameter.
Declaring a parameter to an out method is useful when multiple values need to be returned from a function or method.
It is not compulsory to initialize a parameter value before using it in a calling method.
A parameter value must be initialized within the calling method before its use.
When we use REF, data can be passed bi-directionally.
When we use OUT data is passed only in a unidirectional way (from the called method to the caller method).
Both ref and out are treated differently at run time and they are treated the same at compile time.
Properties are not variables, therefore it cannot be passed as an out or ref parameter.

Thursday, January 14, 2016

Copy a table into new table with and without data - SQL Server

This article explains  how to copy an existing table to new table in SQL Server.
Lets see how to copy an existing table to new table in SQL Server. There are two options. They are
  • Copy only the structure of an existing table into new table
  • Copy only the structure with data of an existing table into new table

Copy only the structure of an existing table into new table:

SELECT * INTO tblNew FROM tblOld WHERE 1=2


The above query will copy the structure of  an existing table(tblOld) into the new table(tblNew).

Copy only the structure with data of an existing table into new table:

SELECT * INTO tblNew FROM tblOld

This is also same like the previous query, but it copies the structure of existing table(tblOld) with data as well into the new table(tblNew).

Note:-  This will not copy indexes, keys, etc.

If you want to copy the entire structure, you need to generate a Create Script of the table. You can use that script to create a new table with the same structure. You can then also dump the data into the new table if you need to.

If you are using Enterprise Manager, just right-click the table and select copy to generate a Create Script.

Wednesday, January 13, 2016

Why we use Static Class

Introduction:
This article explains why we use static class and what main features of a static class are. A static class is basically the same as a non-static class, but there is one difference: a static class cannot be instantiated. In other words, you cannot use the new keyword to create a variable of the class type. Because there is no instance variable, you access the members of a static class by using the class name itself. Read More

If a class is declared as static then the variables and methods should compulsorily be declared as static.

A class can be declared static, indicating that it contains only static members. It is not possible to create instances of a static class using the new keyword. Static classes are loaded automatically by the .NET Framework common language runtime (CLR) when the program or namespace containing the class is loaded.

Use a static class to contain methods that are not associated with a particular object. For example, it is a common requirement to create a set of methods that do not act on instance data and are not associated to a specific object in your code. You could use a static class to hold those methods.

The main features of a static class are:
  • They only contain static members.
  • They cannot be instantiated.
  • They are sealed.
  • They cannot contain Instance Constructors or simply constructors as we know that they are associated with objects and operates on data when an object is created.

Struct in C#

A struct uses syntax similar to a class. It is a type definition. A struct type is a value type that is typically used to encapsulate small groups of related variables, such as the coordinates of a rectangle or the characteristics of an item in an inventory. The following example shows a simple struct declaration:


Example:-

using System;

class Program
{
    public struct Book
    {
    public decimal price;
    public string title;
    public string author;
    public bool IsAvailable;
    };

    static void Main()
    {
    // ... Create struct on stack.
    Book B;
    B.price = 100.00;
    B.title = "MS";
    B.author = "Vepsh";
    B.IsAvailable=true;

    // ... Write struct field.
    Console.WriteLine(B.title);
    }
} 

Output:- MS

Note:-
  • Please notice how, in Main, the struct is created on the stack. No "new" keyword is used. It is used like a value type such as int.
  • Structs can also contain constructors, constants, fields, methods, properties, indexers, operators, events, and nested types, although if several such members are required, you should consider making your type a class instead.
  • Structs can implement an interface but they cannot inherit from another struct. For that reason, struct members cannot be declared as protected.

Conclusion:
Means that struct stores its data in its type. It is not allocated separately on the managed heap. Structs often reside on the evaluation stack. Every program uses simple structs. All value types (int, bool, char) are structs.