Monday, April 30, 2012

UnBoxing Conversions


UnBoxing is the explicit conversion from a reference type to a value type or from an
interface type to a value type that implements the interface.
When unboxing occurs, memory is copied from the managed heap to the stack. For an
unboxing conversion to a given value type to succeed at run time, the value of the source
argument must be a reference to an object that was previously created by boxing a value
of that value type otherwise an exception is thrown.


Example:
int n = 10;
int j;
Object obj;
obj = n;
j = (int)obj;



Explanation:
In the above code segment, another integer variable j is declared. The last statement
performs explicit conversion of object-type to value-type i.e. integer.
Boxing and UnBoxing have performance implications. Every time a value type is boxed,
a new reference type is created and the value type is copied onto the managed heap.
Depending on the size of the value type and the number of times value types are boxed
and unboxed, the CLR can spend a lot of CPU cycles just doing these conversions.
It is recommended to perform boxing and unboxing in a scenario where you have to pass
a value parameter multiple times to a method that accepts a reference parameter. In such
a case, it is advantageous to box the value parameter once before passing it multiple times
to methods that accept reference methods.


Boxing Conversions


Boxing is the implicit conversion of a value type to a reference type or to any interface
type implemented by this value type. This is possible due to the principle of type system
unification where everything is an object.
When boxing occurs, the contents of value type are copied from the stack into the
memory allocated on the managed heap. The new reference type created contains a copy
of the value type and can be used by other types that expect an object reference. The
value contained in the value type and the created reference types are not associated in any
way. If you change the original value type, the reference type is not affected. Boxing,
thus, enables everything to appear to be an object, thereby avoiding the overhead required
if everything actually were an object.

Example:
int n = 10;
Object obj;
obj = n;


Explanation:
In the above code segment, a value-type variable n is declared and is assigned the value
10. The next statement declares an object-type variable obj. The last statement implicitly
performs boxing operation on the variable n.

Why Namespaces


Namespaces are used in .Net to organize class libraries into a hierarchical structure and
reduce conflicts between various identifiers in a program. By helping organize classes,
namespaces help programmers manage their projects efficiently and in a meaningful way
that is understood by consumers of the class library. Namespaces enables reusable
components from different companies to be used in the same program without the worry
of ambiguity caused by multiple instances of the same identifier.
Namespaces provide a logical organization for programs to exist. Starting with a toplevel
namespace, sub-namespaces are created to further categorize code, based upon its
purpose.
In .Net, the base class library begins at the System namespace. There are several classes
at the System level such as Console, Exception etc. The namespace name gives a good
idea of the types of classes that are contained within the namespace. The fully qualified
name of a class is the class name prefixed with the namespace name. There are also
several nested namespaces within the System namespace such as System.Security,
System.IO, System.Data, System.Collections etc.
Reducing conflict is the greatest strength of namespaces. Class and method names often
collide when using multiple libraries. This risk increases as programs get larger and
include more third-party tools.

Structures


A structure allows you to create your own custom data types and it contains one or more
members that can be of different data types. It can contain fields, methods, etc.


Structures are very similar to classes but there are some restrictions present in the case of
structures that are absent in the case of classes. For example you cannot initialize
structure members. Also you cannot inherit a structure whereas classes can be inherited.
Another important feature of structures differentiating it from classes is that a structure
can't have a default parameter-less constructor or a destructor. A structure is created on
the stack and dies when you reach the closing brace in C# or the End structure in
VB.NET.
But one of the most important differences between structures and classes is that structures
are referenced by value and classes by reference. As a value type, allocated on the stack,
structs provide a significant opportunity to increase program efficiency. Objects on the
stack are faster to allocate and de-allocate. A struct is a good choice for data-bound
objects, which don’t require too much memory. The memory requirements should be
considered based on the fact that the size of memory available on the stack is limited than
the memory available on the heap.
Thus we must use classes in situations where large objects with lots of logic are required.

Struct – Code: Sample code showing the Class vs. Structures



using System;
class Test {
int classvar ;
int anothervar =20;
public Test ( )
{
classvar = 28;
}
public static void Main()
{
Test t = new Test();
ExampleStruct strct = new ExampleStruct(20);
System.Console.WriteLine(strct.i);
strct.i = 10;
System.Console.WriteLine(t.classvar);
System.Console.WriteLine(strct.i);
strct.trialMethod();
}
}
struct ExampleStruct {
public int i;
public ExampleStruct(int j)
{
i = j;

}
public void trialMethod()
{
System.Console.WriteLine("Inside Trial Method");
}
}
O/P:-
28
20
10
Inside Trial Method


In the above example, I have declared and used a constructor with a single parameter for
a structure. Instead if I had tried to use a default parameter-less parameter I would have
got an error. But the same is possible in the case of classes as shown by the default
parameter-less constructor, which initializes the classvar variable to 28.
Another point to note is that a variable called anothervar has been declared and initialized
within the class whereas the same cannot be done for members of a structure.




Properties


Properties are named members of classes, structs, and interfaces. They provide a flexible
mechanism to read, write, or compute the values of private fields through accessors.
Properties are an extension of fields and are accessed using the same syntax. Unlike
fields, properties do not designate storage locations. Instead, properties have accessors
that read, write, or compute their values.


Get accessor
The execution of the get accessor is equivalent to reading the value of the field.
The following is a get accessor that returns the value of a private field name:

private string name; // the name field
public string Name // the Name property
{
get
{
return name;
}
}


Set accessor


The set accessor is similar to a method that returns void. It uses an implicit parameter
called value, whose type is the type of the property. In the following example, a set
accessor is added to the Name property:
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
When you assign a value to the property, the set accessor is invoked with an argument
that provides the new value. For example:


e1.Name = "Reshmi"; // The set accessor is invoked here
It is an error to use the implicit parameter name (value) for a local variable declaration in
a set accessor.

How to make a Property Read Only/Write Only
There are times when we may want a property to be read-only – such that it can’t be
changed.
This is where read-only properties come into the picture. A Read Only property is one
which includes only the get accessor, no set accessor.


public read Only int empid
{
get
{
return empid;
}
}
Similar to read-only properties there are also situations where we would need
something known as write-only properties. In this case the value can be changed
but not retrieved. To create a write-only property, use the WriteOnly keyword and
only implement the set block in the code as shown in the example below.


public writeOnly int e
{
set
{
e = value
}
}





Overriding


Class inheritance causes the methods and properties present in the base class also to be
derived into the derived class. A situation may arise wherein you would like to change
the functionality of an inherited method or property. In such cases we can override the
method or property of the base class. This is another feature of polymorphism.


public abstract class shapes
{
public abstract void display()
{
Console.WriteLine("Shapes");
}
}
public class square: shapes
{
public override void display()
{
Console.WriteLine("This is a square");
}
}
public class rectangle:shapes
{
public override void display()
{
Console.WriteLine("This is a rectangle");
}
}

Overloading and Overriding of the Class


Overloading provides the ability to create multiple methods or properties with the same
name, but with different parameters lists. This is a feature of polymorphism. A simple
example would be an addition function, which will add the numbers if two integer
parameters are passed to it and concatenate the strings if two strings are passed to it.


using System;
public class test
{
public int Add(int x , int y)
{
return(x + y);
}
public string Add(String x, String y )
{
return (x + y);
}
public static void Main()
{
test a = new test ();
int b;
String c;
b = a.Add(1, 2);
c = a.Add("Reshmi", " Nair");
Console.WriteLine(b);
Console.WriteLine(c);
}
}
O/P:
3
Reshmi Nair

Using Authorization with Swagger in ASP.NET Core

 Create Solution like below LoginModel.cs using System.ComponentModel.DataAnnotations; namespace UsingAuthorizationWithSwagger.Models {     ...