Santosh - C#.NET Interview Preparation

download Santosh - C#.NET Interview Preparation

of 22

Transcript of Santosh - C#.NET Interview Preparation

  • 7/29/2019 Santosh - C#.NET Interview Preparation

    1/22

    Santosh .NET Training

    Santosh C#.NET Interview Preparation Page 1

    Table of Contents1 Variable Scope:............................................................................................................ 3

    2 Compilation and Assembly.......................................................................................... 3 3 Operators, Expression and Statements ........................................................................ 4

    4 Data Types ................................................................................................................... 5

    4.1 Boolean Types:..................................................................................................... 5

    4.2 Integer Types ........................................................................................................ 5

    4.3 String Type ........................................................................................................... 6

    4.4 Char Type ............................................................................................................. 6

    4.5 Floating Point ....................................................................................................... 6

    4.6 Decimal Types...................................................................................................... 7 4.7 Common Type System (CTS) .............................................................................. 7

    4.8 Special Data Types ............................................................................................... 7

    4.8.1 DateTime Data type ............................................... ...........................................7

    4.8.2 Object data type ............................................. ............................................... ...7

    4.8.3 Enumerations ....................................... ................................................. ...........7

    5 Control/Decision Statements if, Switch and Conditional Statements ...................... 7

    5.1 The if Decision Statement ................................................................................ 8

    5.2 The switch Statement ........................................................................................... 8 5.3 Differences between Switch and If-else ............................................................... 8

    6 Iterations ...................................................................................................................... 9

    6.1 Difference between While loop and the do Loop ................................................ 9

    7 Object Oriented Programming..................................................................................... 9

    7.1 Encapsulation ....................................................................................................... 9

    7.2 Inheritance ............................................................................................................ 9

    7.3 Polymorphism ...................................................................................................... 9

    8 Definitions in OOPs..................................................................................................... 9 8.1 Class ..................................................................................................................... 9

    8.2 Methods ................................................................................................................ 9

    8.3 Fields and Properties .......................................................................................... 10

    8.4 Auto-implemented Properties ............................................................................ 10

    8.5 Instantiat ion of a c lass with a new operator ....................................................... 10

  • 7/29/2019 Santosh - C#.NET Interview Preparation

    2/22

    Santosh .NET Training

    Santosh C#.NET Interview Preparation Page 2

    8.6 Differences between Stack and Heap ................................................................. 10

    8.7 Overriding Methods and Properties ................................................................... 11

    8.7.1 virtual ............................................ ............................................... .................11

    8.8 Constructors ....................................................................................................... 11

    8.9 Overloading Methods and Contructors .............................................................. 11

    9 Abstract ...................................................................................................................... 11

    9.1 Use with Classes................................................................................................. 11

    9.2 Use with Methods............................................................................................... 12

    9.3 Use with Properties ............................................................................................ 12

    10 Interface ................................................................................................................. 12

    10.1 Differences between Interfaces and abstract c lasses .......................................... 13

    11 sealed...................................................................................................................... 14

    12 static ....................................................................................................................... 14 13 Access Modifiers.................................................................................................... 14

    14 Arrays and Collection of Objects........................................................................... 15

    14.1 Arrays ................................................................................................................. 15

    14.2 Arrays of Objects ............................................................................................... 15

    14.3 ArrayList ............................................................................................................ 15

    14.4 Generic Collect ions ............................................................................................ 17

    15 Association of the Objects ..................................................................................... 17

    15.1 Aggregation ........................................................................................................ 17 15.2 Containment/Composition ................................................................................. 17

    16 Value Types ........................................................................................................... 17

    16.1.1 Main Features of Value Types..........................................................................18

    16.2 Value vs. Reference Type .................................................................................. 18

    16.3 struct ................................................................................................................... 19

    16.4 Structs Vs Classes .............................................................................................. 19

    17 Constants ................................................................................................................ 21

    18 Casting ................................................................................................................... 21 19 Boxing and Unboxing ............................................................................................ 21

    20 Object and Collect ion Initializers .......................................................................... 22

    20.1 Object initializers ............................................................................................... 22

    20.2 Collection initializers ......................................................................................... 22

  • 7/29/2019 Santosh - C#.NET Interview Preparation

    3/22

    Santosh .NET Training

    Santosh C#.NET Interview Preparation Page 3

    1 Variable Scope:The code blocks (nothing but the code within the curly braces { }) define the scope of the

    variables.

    2 Compilation and AssemblyCompilat ion is a process that converts human readable C# code into machine-usable/readable code. The end result of a compilation is a file called an assembly. Thereare two types of assemblies.

    1. .exe files (executable assemblies)1. .dll files (dynamic link library) It is a supporting library of code to be used by

    other executing code. Well talk more about them when we try to architect our applicat ion for re-use (interesting).

    The entire compilation process happens in 2 phases.1. The 1 st phase happens when you begin debugging. When you begin debugging, a

    debug version of the assembly will get added in the deb ug folder. We have seenthis in the First C# application path.

    1. Release version of the assembly will get created in the Release folder.

    Debug Assembly Release AssemblyGets created when we start debugging thecode. Will be in Debug folder under bindirectory.

    Will be in Release folder under bindirectory

    Has some additional information added tothe assembly to enable the IDE to

    participate in the execution of theapplication in debug mode.

    If you want to give your application tosomebody else then at a minimum we haveto give them the Release version and theyalso gonna have to have the .NETFrmaework runtime.

    During the Compilation process the compiler takes the C# code and turns it into theassembly file.C# Compiler AssemblyThe compilat ion process does a few things during the process of converting the C# codeto an assembly.

    1. Parsing and Compiling into Common Intermediate Languagea. It starts by parsing and validating your C# code.

    b. Once it passes the first check then it converts the C# code to commonIntermediate language (CIL or intermediate language IL).

  • 7/29/2019 Santosh - C#.NET Interview Preparation

    4/22

    Santosh .NET Training

    Santosh C#.NET Interview Preparation Page 4

    c. Compiler adds the bootstrap code calling the .NET runtime. It adds anyadditional programs that need to go along with this assembly or executablefile.

    1. Just-In-Time Compilation (JIT).d. Looking at end users configuration and hardware, this compiler is going

    to create and save the application (optimized version) in a cache for futureuse on t he end users hard drive. So, whenever the application is ran againon the end users machine the .NET Runtime will use the optimizedversion that cached on their machine.

    NOTE: This is all done in the background without the knowledge of a developer.

    3 Operators, Expression and StatementsStatements : It is a complete instruction. It contains one or more expressions.Expressions : They are made up of operators and operands.

    If you look at the previous code line we wrote, we used a condition statement

    if (input == "y" )

    input == "y" is an expression and the whole sentence is a statement.

    In the same way in the below line of code.b = a + 10;

    a + 10 is an expressiona is an operand and + is operator.

    Operands : They are nothing but variables (like a, b in our previous examples), Literalstrings (like "Hello World!" ), and Objects ( like Console class. W ell talk about themin the future sessions).Operators : Below are some operators used in C# language.

    Below is the screenshot listing various operators used in C#.

  • 7/29/2019 Santosh - C#.NET Interview Preparation

    5/22

    Santosh .NET Training

    Santosh C#.NET Interview Preparation Page 5

    4 Data TypesBelow are different types of data that comes with C# language.

    1. Boolean type1. Integrals Numerical1. Floating Point Numerical1. Decimal Numerical1. String

    4.1 Boolean Types:They are declared using the keyword bool .bool isCorrect = false ;

    The value will be either true or false . The space occupied by a Boolean variable is 1 byte (8 bits).

    4.2

    Integer TypesThese are numeric values either signed or unsigned holding values with no decimal points.Below is the table that lists all the integral data types .

  • 7/29/2019 Santosh - C#.NET Interview Preparation

    6/22

    Santosh .NET Training

    Santosh C#.NET Interview Preparation Page 6

    4.3 String TypeThese are textual data surrounded by double quotes or a sequence o f text characters.Below are some character escape sequences

    4.4 Char TypeThis represents a single Unicode character numerically.

    4.5 Floating Point In C# the floating point types are float and double. They are used for real numbers. See

    below for the size and precisions. Floating point types are used when you need to performoperations requiring fract ional representations.

  • 7/29/2019 Santosh - C#.NET Interview Preparation

    7/22

    Santosh .NET Training

    Santosh C#.NET Interview Preparation Page 7

    4.6 Decimal TypesDecimal types will be used for storing money (in the financial cases where you do notwish to round the figures).

    4.7 Common Type System (CTS)One of the main services .NET provides is this CTS. All the data types like int, string (not

    just in C# but in any language supported by .NET ) will be extended out from thecommon data types in this CTS.int from System. Int32 string from System. String Each data type has some limits on what it can store and those limits are based on the sizeof the variable.

    4.8 Special Data Types

    4.8.1 DateTime Data typeThere is a special data type System. DateTime which belong to the .NET Framework class Library (FCL) and there is no equivalent data type for it in C#. This data type isused to deal with date and time re lated data/values.

    4.8.2 Object data typeThe object type is referenced from System. Object data type in .NET Framework.Values of any type can be assigned to the variables of type object. This is the one fromwhich all the other reference types derive.

    int i = 10;object obj;obj = i; //integer valueobj = "something" ; //string value

    4.8.3 EnumerationsEnumeration is a special kind of type that only has certain values defined as possiblevalues.Console .ForegroundColor = ConsoleColor .Blue;

    5 Control/Decision Statements if, Switch and ConditionalStatements

    In this section youll learn the following 1. if statements.

  • 7/29/2019 Santosh - C#.NET Interview Preparation

    8/22

    Santosh .NET Training

    Santosh C#.NET Interview Preparation Page 8

    1. switch statement.1. how break is used in switch statements.1. proper use of the goto statement.

    5.1 The if Decision Statement if is one of the conditional statements in C# which can be used to decide something inthe program.

    5.2 The switch Statement The switch statement is another form of selection statement. This executes a set of logicdepending on the value of a given parameter. Below are the types of the values a switchstatement operates on

    a. Booleans b. Enums (youll learn more about them in the next sessions). c. integral typesd. strings

    Below are the branching statements we use with switch statements.break: Leaves the switch block continue: Leaves the switch block, skips remaining logic in enclosing loop, and goes

    back to loop condition to determine if loop should be executed again from the beginning.Works only if switch statement is in a loop.goto: Leaves the switch block and jumps directly to a label of the form ":"return: Leaves the current method. Well talk more about Methods in the next sessions. throw: Throws an exception. Well talk more about them in the next sessions.

    5.3 Differences between Switch and If-else

    Below are some of the differences between switch and if statements.switch

    a. More readable because of its compactness b. If you omit the break between two switch cases, you can fall through to the next

    case.c. Switch only accepts primitive types as key and constants as cases. This means it

    can be optimized by the compiler using a jump table which is very fast.

    if-elsea. if allows complex expressions in the condition while switch wants a constant

    b. With if else you'd need a goto

    For inline options, we can use conditional statements as we have discussed in the earlier sections.

  • 7/29/2019 Santosh - C#.NET Interview Preparation

    9/22

    Santosh .NET Training

    Santosh C#.NET Interview Preparation Page 9

    6 IterationsLoops allow you to execute a block of statements repeatedly. C# has several statementsto construct loops with, including the while , do, for , and foreach loops.

    6.1 Difference between While loop and the do Loop

    A do loop is similar to the while loop. The only difference is that it checks its condition atthe end of the loop which means that the do loop is guaranteed to execute at least onetime.

    7 Object Oriented ProgrammingC# is an Object oriented programming language. OOPs is nothing but a way or anapproach to simplify the task of building software. OOPs helps you write programs thatare easily maintainable and help us re-use code.

    7.1 EncapsulationIt is the process of keeping the details of an implementation of an object as private. Itenforces Black Box programming. Changes to the code in the black box (interface)should not affect the interfac e. Lets see how to implement the encapsulation usingMethods, F ields and Properties.

    7.2 InheritanceInheritance is a way to reuse code of existing objects, or to establish a subtype from anexisting object, or both

    7.3 PolymorphismPolymorphism is another primary concept of OOPs. It allows you to invoke derived classmethods through a base class reference during run-time.

    I t is the ability of the code to act like many different things but still be treated the same .

    8 Definitions in OOPs

    8.1 ClassClasses are b lue prints to create new instances of objects and defines its fields, methodsand properties.

    8.2 MethodsMethod is a block of code that has a name. It can accept parameters and may return avalue.METHOD HEADER The entire definition as shown below from Accelerate method is called Method Header.Header includes the data types and the names of the parameters.public int Accelerate( int increaseBy)

    METHOD SIGNATURE Signature includes only the data types.public int Accelerate( int )

    http://en.wikipedia.org/wiki/Reusabilityhttp://en.wikipedia.org/wiki/Subtype_polymorphismhttp://en.wikipedia.org/wiki/Subtype_polymorphismhttp://en.wikipedia.org/wiki/Reusability
  • 7/29/2019 Santosh - C#.NET Interview Preparation

    10/22

    Santosh .NET Training

    Santosh C#.NET Interview Preparation Page 10

    8.3 Fields and PropertiesFields define the state or attributes of an object.Advantage of properties over fields is that you can change their internal implementationwithout breaking the code (or changing the interface of the object). You can dovalidations also before setting the values to fields.

    8.4 Auto-implemented PropertiesThese are used to reduce the amount of coding.

    These can also be written as

    8.5 Instantiation of a class with a new operatorThe steps taken to create a new instance of a class is called as instantiation. The newoperator is used to instantiate a class. See below for the way we instantiate car class.

    Car c;

    c = new Car ();

    8.6 Differences between Stack and HeapStack Heap

    1 organized grouping of information unorganized grouping of information

    2 Stack is where the value types of integer and other simple types are stored

    Heap is where referencetypes like string object,

    datetime object, customobjects are stored

    3 Stack is organized and easy for theapplication to find what it is looking for

    because it knows the exact size of each of those objects and they are typically small

    Since this informationvaries and typicallymuch larger they are

    piled in the heap

  • 7/29/2019 Santosh - C#.NET Interview Preparation

    11/22

    Santosh .NET Training

    Santosh C#.NET Interview Preparation Page 11

    in size wherever they gonna fitand is accessed throughan address

    4

    8.7 Overriding Methods and PropertiesYou can also override the base classs methods or properties in the derived class. You have to use virtual and Override keywords to override a base class method inderived class.

    8.7.1 virtual

    The virtual keyword to specify that a member can be overridable. The implementation of avirtual member can be changed by an overriding member in a derived class.

    You can also use the new keyword in the derived class method.

    8.8 ConstructorsIt is a special kind of method that automatically is called each time we call the newoperator. It is used for initializing the object to get the object into its right state beforestarting to use it.Constructor has the same name as the class name. Even though there is not a return valuedefined in the constructor it is implied that it is always void.

    8.9 Overloading Methods and ContructorsIt allows the programmer to define several methods with the same name, as long as theytake a different set of parameters. Method signatures would be different but the methodname would be same.Method overloading will be used to provide different methods that do semantically samething. It is used instead of allowing default arguments. Use a consistent ordering andnaming pattern for method parameters.Same way you can also overload constructors to initialize differently.

    9 Abstract The abstract modifier can be used with classes, methods, properties, indexers, and

    events.9.1 Use with ClassesUse the abstract modifier in a class declaration to indicate that a class is intended only to

    be a base class of other classes.Abstract classes have the following features:

    An abstract class cannot be instantiated.

    http://msdn.microsoft.com/en-us/library/ebca9ah3%28v=vs.71%29.aspxhttp://msdn.microsoft.com/en-us/library/ebca9ah3%28v=vs.71%29.aspx
  • 7/29/2019 Santosh - C#.NET Interview Preparation

    12/22

    Santosh .NET Training

    Santosh C#.NET Interview Preparation Page 12

    An abstract class may contain abstract methods and accessors.You cannot use abstract class with sealed modifier because it will be of no use.A non-abstract class derived from an abstract c lass must include actualimplementations o f all inherited abstract methods and accessors.

    9.2 Use with MethodsUse the abstract modifier in a method or property declaration to indicate that the method orproperty does not contain implementation.

    Abstract methods have the following features:

    An abstract method is implicitly a virtual method.Abstract method declarations are only permitted in abstract classes.There is no method body; the method declaration simply ends with a semicolonand there are no braces ({ }) following the signature. For example:

    public abstract void MyMethod();

    The implementation is provided by an overriding method, which is a member of anon-abstract class.It is an error to use the static or virtual modifiers in an abstract methoddeclaration.

    9.3 Use with Properties

    Abstract properties behave like abstract methods, except for the differences in declaration and

    invocation syntax.

    It is an error to use the abstract modifier on a static property.An abstract inherited property can be overridden in a derived class by including a

    property declaration that uses the override modifier.

    10 Interface

    An interface contains only the signatures of methods, delegates or events. The implementationof the methods is done in the class that implements the interface, as shown in the followingexample:

    An interface can be a member of a namespace or a class, It can contain signatures of thefollowing members:

    1. Methods

    1. Properties

    http://msdn.microsoft.com/en-us/library/ms173114%28v=vs.80%29.aspxhttp://msdn.microsoft.com/en-us/library/w86s7x04%28v=vs.80%29.aspxhttp://msdn.microsoft.com/en-us/library/w86s7x04%28v=vs.80%29.aspxhttp://msdn.microsoft.com/en-us/library/ms173114%28v=vs.80%29.aspx
  • 7/29/2019 Santosh - C#.NET Interview Preparation

    13/22

    Santosh .NET Training

    Santosh C#.NET Interview Preparation Page 13

    1. Indexers

    1. Events

    An interface can inherit from one or more base interfaces.

    When a class is derived from both base class and interface, the base class should always be listed first followed by the interfaces. See belowclass Student : Person, IHuman

    10.1 Differences between Interfaces and abstract classesFeature Interface Abstract class

    Multiple inheritance A class may inherit severalinterfaces.

    A class may inherit onlyone abstract c lass.

    Default implementation An interface cannot provideany code, just the headers.

    An abstract class can provide complete, defaultcode and/or just the detailsthat have to be overridden.

    Access Modifiers An interface cannot haveaccess modifiers for themethods and properties.Everything is assumed as

    public

    An abstract class cancontain access modifiers

    Core VS Peripheral Interfaces are used to define

    the peripheral abilities of aclass. In other words bothHuman and Vehicle caninherit from a IMovableinterface.

    An abstract class defines

    the core identity of a classand there it is used for objects of the same type.

    Homogeneity If various implementationsonly share method signaturesthen it is better to useInterfaces.

    If various implementationsare of the same kind and usecommon behaviour or statusthen abstract class is better touse.

    Speed Requires more time to findthe actual method in thecorresponding classes.

    Fast

    Adding functionality(Versioning)

    If we add a new method toan Interface then we have totrack down all theimplementations of theinterface and define

    If we add a new method toan abstract class then wehave the option of

    providing defaultimplementation and

    http://msdn.microsoft.com/en-us/library/2549tw02%28v=vs.80%29.aspxhttp://msdn.microsoft.com/en-us/library/8627sbea%28v=vs.80%29.aspxhttp://msdn.microsoft.com/en-us/library/8627sbea%28v=vs.80%29.aspxhttp://msdn.microsoft.com/en-us/library/2549tw02%28v=vs.80%29.aspx
  • 7/29/2019 Santosh - C#.NET Interview Preparation

    14/22

    Santosh .NET Training

    Santosh C#.NET Interview Preparation Page 14

    implementation for the newmethod.

    therefore all the existingcode might work properly.

    Fields and Constants No fields can be defined ininterfaces

    An abstract class can havefields and constants defined

    11 sealedA sealed class cannot be inherited. It is an error to use a sealed class as a base c lass. Usethe sealed modifier in a class declaration to prevent inheritance of the class.It is not permitted to use the abstract modifier with a sea led class.Structs are implicitly sealed; therefore, they cannot be inherited.

    12 staticUse the static modifier to declare a static member, which be longs to the type itself rather than to a specific object. The static modifier can be used with fields, methods, properties,operators, events and constructors, but cannot be used with indexers, destructors.A static member cannot be referenced through an instance. Instead, it is referencedthrough the type name.

    13 Access ModifiersModifier Description

    Public There are no restrictions on accessing

    public members.

    Private Access is limited to within the classdefinition. This is the default accessmodifier type if none is formally specified

    Protected Access is limited to within the classdefinition and any class that inherits fromthe class

    Internal Access is limited exclusive ly to classesdefined within the current project assembly

    protected internal Access is limited to the current assemblyand types derived from the containingclass. All members in current project andall members in derived class can access the

    http://msdn.microsoft.com/en-us/library/sf985hc5%28v=vs.71%29.aspxhttp://msdn.microsoft.com/en-us/library/sf985hc5%28v=vs.71%29.aspx
  • 7/29/2019 Santosh - C#.NET Interview Preparation

    15/22

    Santosh .NET Training

    Santosh C#.NET Interview Preparation Page 15

    variables.

    14 Arrays and Collection of Objects

    14.1 ArraysArrays are collections of data. You can use it like any other variable but inside it containsmore than 1 va lue (a co llection of data). You can access the data from array variableusing an index.string [] names = new string [3]; Above line is the way of declaring and initializing an array.

    The square brackets [] are called the index access operator and this is what we lluse to access a specific element of array.The array elements are 0 based.

    Arrays are of fixed size.

    14.2 Arrays of ObjectsJust like we use Arrays to work with value types like int and string they can also be usedto work with Custom types.

    There are d isadvantages in using Array for collection of custom types.1. You need to know how many items you need to be in the array to begin with. You

    cannot dynamically add the items to th is array as it would throw the out of

    range exception. 1. You cannot remove an item from the array because the array should be of the sizementioned while declaring it.

    So, using Arrays of objects is of limited use.

    14.3 ArrayList To overcome the above problems, we can use ArrayList. Below is how we wouldinitialize an ArrayList.

  • 7/29/2019 Santosh - C#.NET Interview Preparation

    16/22

    Santosh .NET Training

    Santosh C#.NET Interview Preparation Page 16

    ArrayList class belongs to System.Collections namespace.We use a method called Add from ArrayList class to add the object to the arraylist.

    Instead of assigning it at a specific index in case of Array we are just adding it to theArrayList here.Using the ArrayList,

    You can add and remove any number of items dynamically.

    The advantages of using ArrayList over Array are1. you do not have to specify the number of items you are going to add to the

    arraylist (where in the case of you would have to mention it while declaring).

  • 7/29/2019 Santosh - C#.NET Interview Preparation

    17/22

    Santosh .NET Training

    Santosh C#.NET Interview Preparation Page 17

    1. You can easily remove or add the objects dynamically.1. You can insert items at a specific position.

    The disadvantages of ArrayList1. It is a bit cumbersome because everything in the collection will be saved as type

    System.Object. So, when we get the item out of collection we have to cast it back to the custom type before start using the item. It can break the code if you add anytype of the custom objects because you have to cast the items.

    14.4 Generic CollectionsIn order to overcome the problems with ArrayList, in .NET v2.0 Generic collections wasintroduced.Every item in the collection is guaranteed to be the exact same type. List is a class to doa generic collection and this belongs to System.Collections.Generic namespace.

    T means any Type.

    15 Association of the ObjectsThere are two basic types of associat ions (relationships).

    1. Aggregation1. Containment/Composition

    15.1 AggregationAggregation is the (* the *) relationship between two classes. When object o f one classhas an (* has *) object of another, then we called that there is an aggregation between twoclasses.

    15.2 Containment/CompositionDefining a class with in a class is called containment.

    16 Value TypesThe value types consist of two main categories:

    StructsEnumerations

    Structs fall into these categories:

    Numeric typeso Integral typeso Floating-point types

  • 7/29/2019 Santosh - C#.NET Interview Preparation

    18/22

    Santosh .NET Training

    Santosh C#.NET Interview Preparation Page 18

    o decimalboolUser defined structs.

    16.1.1 Main Features of Value Types

    Variables that are based on value types directly contain values.Assigning one value type variable to another copies the contained value. This differsfrom the assignment of reference type variables, which copies a reference to the objectbut not the object itself.All value types are derived implicitly from the System.ValueType.Unlike with reference types, you cannot derive a new type from a value type.Like reference types, structs can implement interfaces.Unlike reference types, a value type cannot contain the null value. However, thenullable types feature does allow for values types to be assigned to null.

    o Nullable types are instances of the System.Nullable struct. A nullable typecan represent the correct range of values for its underlying value type, plus anadditional null value. For example, a Nullable, pronounced "Nullable of Int32," can be assigned any value from -2147483648 to 2147483647, or it canbe assigned the null value.

    Each value type has an implicit default constructor that initializes the default value of that type. For information about default values of value types, see below for the DefaultValues Table.

    16.2 Value vs. Reference Type

    With value types:

    Value type ass ignments copy all members the whole value - this copies all members of one value to another making two complete instances. Value types passed by parameter or returned from methods/properties copywhole value - this behavior is the same as value assignment. Value types assigned to an object are boxed that is, they are surrounded by anobject and then passed by reference. Value types are destroyed when they pass out of scope - local variables and

    parameters are typically cleaned up when scope is exited, members of anenclosing type are cleaned up when the enclosing type is cleaned up. Value types may be created on the stack or heap as appropriate - typically

    parameters and locals are created on the stack, members of an enclosing classare typically on the heap. Value types cannot be null - default value of members that are primitive is zero,default value of members that are a struct is an instance with all struct membersdefaulted.

    In contrast, with reference types:

    http://void%280%29/http://void%280%29/http://msdn.microsoft.com/en-us/library/b3h38hb0.aspxhttp://msdn.microsoft.com/en-us/library/b3h38hb0.aspxhttp://void%280%29/
  • 7/29/2019 Santosh - C#.NET Interview Preparation

    19/22

    Santosh .NET Training

    Santosh C#.NET Interview Preparation Page 19

    Reference type assignment only copies the reference - thisdecrements/increments reference counts as appropriate. Reference types passed by parameter or returned from methods/propertiespass a reference - the reference is copied, but both references refer to the sameoriginal object.

    Reference types are only destroyed when garbage collected - after all references to the object are determined to be unreachable. Reference types are generally on the heap - its always possible compiler mayoptimize, but in general you should always think of them as heap objects Reference types can be null - default value of members that are reference typesmembers is null.

    16.3 struct

    A struct type is a value type that is typically used to encapsulate small groups of relatedvariables. The following example shows a simple struct declaration:

    public struct Book{

    public decimal price;public string title;public string author;

    }

    Structs can also contain constructors, constants, fields, methods, properties, indexers,operators, events, and nested types, although if several such members are required, you shouldconsider 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.

    16.4 Structs Vs Classes

    Feature Struct Class Notes

    Is a reference type? No Yes*Is a value type? Yes NoCan have nested Types (enum, class,struct)?

    Yes Yes

    Can have constants? Yes YesCan have fields? Yes* Yes Struct instance fields

    cannot be initialized,will automatically

  • 7/29/2019 Santosh - C#.NET Interview Preparation

    20/22

    Santosh .NET Training

    Santosh C#.NET Interview Preparation Page 20

    initialize to default value.

    Can have properties? Yes YesCan have indexers Yes YesCan have methods? Yes YesCan have events? Yes* Yes Structs, like classes,

    can have events, but care must be taken that ou dont subscribe to

    a copy of a struct instead of the struct ou intended.

    Can have static members(constructors, fields, methods,properties, etc.)?

    Yes Yes

    Can inherit? No* Yes* Classes can inherit rom other classes (or

    object by default).Structs always inherit rom

    System.ValueType and are sealed implicitly

    Can implement interfaces? Yes YesCan ove rload constructor? Yes* Yes Struct overload of

    constructor does not hide default constructor.

    Can define default constructor? No Yes The struct default constructor initializesall instance fields todefault values and cannot be changed.

    Can ove rload operators? Yes YesCan be generic? Yes YesCan be partial? Yes YesCan be sealed? Always* Yes Structs are always

    sealed and can never

    be inherited from. Can be referenced in instancemembers using this keyword?

    Yes* Yes In structs, this is avalue variable, inclasses, it is a readonlyreference.

    Needs new operator to createinstance?

    No* Yes C# classes must beinstantiated using new.

    However, structs do

  • 7/29/2019 Santosh - C#.NET Interview Preparation

    21/22

    Santosh .NET Training

    Santosh C#.NET Interview Preparation Page 21

    not require this. Whilenew can be used on a

    struct to call aconstructor, you canelect not to use new

    and init the fieldsourself, but you must init all fields and theields must be public!

    17 ConstantsConstants are immutable (changeless) values which are known at compile time and donot change for the life of the program. Constants are declared with the const modifier.

    18 Casting

    Converting between data types can be done explicitly using a cast, but in some cases,implicit conversions are a llowed. For example:

    static void TestCasting(){int i = 10;float f = 0;f = i; // An implicit conversion, no data will be lost. f = 0.5F;i = ( int)f; // An explicit conversion. Information will be lost.

    }

    19 Boxing and Unboxing

    Boxing is the process of converting a value type to the type object or to any interface typeimplemented by this value type.

    In the following example, the integer variable i is boxed and assigned to object o.

    int i = 123;// The following line boxes i.

  • 7/29/2019 Santosh - C#.NET Interview Preparation

    22/22

    Santosh .NET Training

    Santosh C#.NET Interview Preparation Page 22

    object o = i;

    Unboxing extracts the value type from the object. Boxing is implicit; unboxing is explicit.

    The object o can then be unboxed and assigned to integer variable i:

    o = 123;i = (int )o; // unboxing

    20 Object and Collection Initializers

    20.1 Object initializersThese let you assign values to any accessible fields or properties o f an object at creationtime without having to explicitly invoke a constructor. The following example showshow to use an object initializer with a named type, Cat. Note the use of auto-implemented

    properties in the Cat class.class Cat{

    // Auto-implemented properties.public int Age { get ; set ; }public string Name { get ; set ; }

    }

    20.2 Collection initializersThese let you specify one or more element intializers, when you initialize a collectionclass that implements IEnumerable. The element initializers can be a simple value, a nexpression or an object initializer. By using a collection initializer you do not have tospecify multiple calls to the Add method of the class in your source code; the compiler

    adds the calls.The following examples shows two simple collection initializers:

    List < int > digits = new List < int > { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9};

    List < int > digits2 = new List < int > { 0 + 1, 12 % 3, MakeInt() };

    The following collection initializer uses object initializers to initialize objects of the Catclass defined in a previous example. Note that the individual object initializers areenclosed in braces and separated by commas.

    List < Cat > cats = new List < Cat >{

    new Cat (){ Name = "Sylvester" , Age=8 },new Cat (){ Name = "Whiskers" , Age=2 },new Cat (){ Name = "Sasha" , Age=14 }

    };

    You can specify null as an element in a collection initializer if the collection's Add method allows it.

    List < Cat > moreCats = new List < Cat >{

    new Cat (){ Name = "Furrytail" , Age=5 },new Cat (){ Name = "Peaches" , Age=4 },null

    };

    http://msdn.microsoft.com/en-us/library/system.collections.ienumerable.aspxhttp://msdn.microsoft.com/en-us/library/system.collections.ienumerable.aspx