Santosh - C#.NET Interview Preparation

Published on June 2016 | Categories: Documents | Downloads: 43 | Comments: 0 | Views: 250
of 22
Download PDF   Embed   Report

Santosh Khuray - C#(Irving tx)

Comments

Content

Santosh .NET Training

Table of Contents
1 2 3 4 Variable Scope:............................................................................................................ 3 Compilation and Assembly.......................................................................................... 3 Operators, Expression and Statements ........................................................................ 4 Data Types ................................................................................................................... 5 4.1 4.2 4.3 4.4 4.5 4.6 4.7 4.8
4.8.1 4.8.2 4.8.3

Boolean Types:..................................................................................................... 5 Integer Types ........................................................................................................ 5 String Type ........................................................................................................... 6 Char Type ............................................................................................................. 6 Floating Point ....................................................................................................... 6 Decimal Types...................................................................................................... 7 Common Type System (CTS) .............................................................................. 7 Special Data Types ............................................................................................... 7
DateTime Data type ..........................................................................................7 Object data type ...............................................................................................7 Enumerations...................................................................................................7

5

Control/Decision Statements – if, Switch and Conditional Statements ...................... 7 5.1 5.2 5.3 The” if” Decision Statement ................................................................................ 8 The switch Statement ........................................................................................... 8 Differences between Switch and If-else ............................................................... 8 Difference between While loop and the do Loop ................................................ 9 Encapsulation ....................................................................................................... 9 Inheritance ............................................................................................................ 9 Polymorphism ...................................................................................................... 9 Class ..................................................................................................................... 9 Methods ................................................................................................................ 9 Fields and Properties .......................................................................................... 10 Auto- implemented Properties ............................................................................ 10 Instantiation of a class with a new operator ....................................................... 10
Page 1

6 7

Iterations ...................................................................................................................... 9 6.1 7.1 7.2 7.3 Object Oriented Programming..................................................................................... 9

8

Definitions in OOPs..................................................................................................... 9 8.1 8.2 8.3 8.4 8.5

Santosh – C#.NET Interview Preparation

Santosh .NET Training 8.6 8.7
8.7.1

Differences between Stack and Heap ................................................................. 10 Overriding Methods and Properties ................................................................... 11
virtual ............................................................................................................11

8.8 8.9 9 9.1 9.2 9.3 10 10.1 11 12 13 14 14.1 14.2 14.3 14.4 15 15.1 15.2 16 16.2 16.3 16.4 17 18 19 20 20.1 20.2

Constructors ....................................................................................................... 11 Overloading Methods and Contructors .............................................................. 11 Use with Classes................................................................................................. 11 Use with Methods............................................................................................... 12 Use with Properties ............................................................................................ 12 Interface ................................................................................................................. 12 Differences between Interfaces and abstract classes .......................................... 13 sealed...................................................................................................................... 14 static ....................................................................................................................... 14 Access Modifiers.................................................................................................... 14 Arrays and Collection of Objects........................................................................... 15 Arrays ................................................................................................................. 15 Arrays of Objects ............................................................................................... 15 ArrayList ............................................................................................................ 15 Generic Collections ............................................................................................ 17 Association of the Objects ..................................................................................... 17 Aggregation ........................................................................................................ 17 Containment/Composition ................................................................................. 17 Value Types ........................................................................................................... 17
Main Features of Value Types..........................................................................18

Abstract ...................................................................................................................... 11

16.1.1

Value vs. Reference Type .................................................................................. 18 struct ................................................................................................................... 19 Structs Vs Classes .............................................................................................. 19 Constants ................................................................................................................ 21 Casting ................................................................................................................... 21 Boxing and Unboxing ............................................................................................ 21 Object and Collection Initializers .......................................................................... 22 Object initializers ............................................................................................... 22 Collection initializers ......................................................................................... 22

Santosh – C#.NET Interview Preparation

Page 2

Santosh .NET Training

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

2 Compilation and Assembly
Compilation is a process that converts human readable C# code into machineusable/readable code. The end result of a compilation is a file called an assembly. There are 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. We’ll talk more about them when we try to architect our application for re- use (interesting). The entire compilation process happens in 2 phases. 1. The 1st phase happens when you begin debugging. When you begin debugging, a debug version of the assembly will get added in the debug folder. We have seen this in the First C# application path. 1. Release version of the assembly will get created in the Release folder. Debug Assembly Gets created when we start debugging the code. Will be in Debug folder under bin directory. Has some additional information added to the assembly to enable the IDE to participate in the execution of the application in debug mode. Release Assembly Will be in Release folder under bin directory If you want to give your application to somebody else then at a minimum we have to give them the Release version and they also gonna have to have the .NET Frmaework runtime.

During the Compilation process the compiler takes the C# code and turns it into the assembly file. C#  Compiler  Assembly The compilation process does a few things during the process of converting the C# code to an assembly. 1. Parsing and Compiling into Common Intermediate Language a. It starts by parsing and validating your C# code. b. Once it passes the first check then it converts the C# code to common Intermediate language (CIL or intermediate language IL).

Santosh – C#.NET Interview Preparation

Page 3

Santosh .NET Training c. Compiler adds the bootstrap code calling the .NET runtime. It adds any additional programs that need to go along with this assembly or executable file. 1. Just-In-Time Compilation (JIT). d. Looking at end user’s configuration and hardware, this compiler is going to create and save the application (optimized version) in a cache for future use on t he end users’ hard drive. So, whenever the application is ran again on the end users’ machine the .NET Runtime will use the optimized version that cached on their machine. NOTE: This is all done in the background without the knowledge of a developer.

3 Operators, Expression and Statements
Statements: 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 expression a is an operand and + is operator.

Operands: They are nothing but variables (like a, b in our previous examples), Literal strings (like "Hello World!"), and Objects (like Console class. W e’ll talk about them in the future sessions). Operators: Below are some operators used in C# language. Below is the screenshot listing various operators used in C#.

Santosh – C#.NET Interview Preparation

Page 4

Santosh .NET Training

4 Data Types
Below are different types of data that comes with C# language. 1. Boolean type 1. Integrals  Numerical 1. Floating Point  Numerical 1. Decimal  Numerical 1. 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 Types
These are numeric values either signed or unsigned holding values with no decimal points. Below is the table that lists all the integral data types .

Santosh – C#.NET Interview Preparation

Page 5

Santosh .NET Training

4.3 String Type
These are textual data surrounded by double quotes or a sequence of text characters.
Below are some character escape sequences

4.4 Char Type
This 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 perform operations requiring fractional representations.

Santosh – C#.NET Interview Preparation

Page 6

Santosh .NET Training

4.6 Decimal Types
Decimal types will be used for storing money (in the financial cases where you do not wish 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 the common 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 size of the variable.

4.8 Special Data Types
4.8.1 DateTime Data type There 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 is used to deal with date and time related data/values. 4.8.2 Object data type The 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 from which all the other reference types derive.
int i = 10; object obj; obj = i; //integer value obj = "something"; //string value

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

5 Control/Decision Statements – if, Switch and Conditional Statements
In this section you’ll learn the following 1. if statements.
Santosh – C#.NET Interview Preparation Page 7

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

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

5.2 The switch Statement
The switch statement is another form of selection statement. This executes a set of logic depending on the value of a given parameter. Below are the types of the values a switch statement operates on a. Booleans b. Enums (you’ll learn more about them in the next sessions). c. integral types d. 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 "<labelname>:" return: Leaves the current method. We’ll talk more about Methods in the next sessions. throw: Throws an exception. We’ll 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 it’s 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-else a. 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.

Santosh – C#.NET Interview Preparation

Page 8

Santosh .NET Training

6 Iterations
Loops allow you to execute a block of statements repeatedly. C# has several statements to 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 at the end of the loop which means that the do loop is guaranteed to execute at least one time.

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

7.1 Encapsulation
It is the process of keeping the details of an implementation of an object as private. It enforces “Black Box” programming. Changes to the code in the black box (interface) should not affect the interface. Let’s see how to implement the encapsulation using Methods, Fields and Properties.

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

7.3 Polymorphism
Polymorphism is another primary concept of OOPs. It allows you to invoke derived class methods through a base class reference during run-time. It is the ability of the code to act like many different things but still be treated the same .

8 Definitions in OOPs
8.1 Class
Classes are blue prints to create new instances of objects and defines its fields, methods and properties.

8.2 Methods
Method is a block of code that has a name. It can accept parameters and may return a value. 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)

Santosh – C#.NET Interview Preparation

Page 9

Santosh .NET Training

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

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

These can also be written as

8.5 Instantiation of a class with a new operator
The steps taken to create a new instance of a class is called as instantiation. The new operator 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 Heap
Stack 1 organized grouping of information Heap unorganized grouping of information Heap is where reference types like string object, datetime object, custom objects are stored Since this information varies and typically much larger they are piled in the heap
Page 10

2

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

3

Stack is organized and easy for the application to find what it is looking for because it knows the exact size of each of those objects and they are typically small

Santosh – C#.NET Interview Preparation

Santosh .NET Training in size wherever they gonna fit and is accessed through an address

4

8.7 Overriding Methods and Properties
You can also override the base class’s methods or properties in the derived class. You have to use virtual and Override keywords to override a base class method in derived class. 8.7.1 virtual
The virtual keyword to specify that a member can be overridable. The implementation of a virtual member can be changed by an overriding member in a derived class.

You can also use the ne w keyword in the derived class method.

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

8.9 Overloading Methods and Contructors
It allows the programmer to define several methods with the same name, as long as they take a different set of parameters. Method signatures would be differe nt but the method name would be same. Method overloading will be used to provide different methods that do semantically same thing. It is used instead of allowing default arguments. Use a consistent ordering and naming 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 Classes
Use 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.
Santosh – C#.NET Interview Preparation Page 11

Santosh .NET Training 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 class must include actual implementations of all inherited abstract methods and accessors.

9.2 Use with Methods
Use the abstract modifier in a method or property declaration to indicate that the method or property 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 semicolon and 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 a non-abstract class. It is an error to use the static or virtual modifiers in an abstract method declaration.

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 ove rride modifier.

10 Interface
An interface contains only the signatures of methods, delegates or events. The implementation of the methods is done in the class that implements the interface, as shown in the following example: An interface can be a member of a namespace or a class, It can contain signatures of the following members: 1. Methods 1. Properties Santosh – C#.NET Interview Preparation Page 12

Santosh .NET Training
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 below class Student : Person, IHuman

10.1 Differences between Interfaces and abstract classes
Feature Inte rface
Abstract class

Multiple inheritance Default implementation

A class may inherit several interfaces. An interface cannot provide any code, just the headers.

Access Modifiers

An interface cannot have access modifiers for the methods and properties. Everything is assumed as public Interfaces are used to define the peripheral abilities of a class. In other words both Human and Vehicle can inherit from a IMovable interface.
If various implementations only share method signatures then it is better to use Interfaces.

A class may inherit only one abstract class. An abstract class can provide complete, default code and/or just the details that have to be overridden. An abstract class can contain access modifiers

Core VS Peripheral

An abstract class defines the core identity of a class and there it is used for objects of the same type.

Homogeneity

If various implementations are of the same kind and use common behaviour or status then abstract class is better to use.

Speed

Adding functionality (Versioning)

Requires more time to find the actual method in the corresponding classes. If we add a new method to an Interface then we have to track down all the implementations of the interface and define

Fast

If we add a new method to an abstract class then we have the option of providing default implementation and
Page 13

Santosh – C#.NET Interview Preparation

Santosh .NET Training implementation for the new method. Fields and Constants
No fields can be defined in interfaces

therefore all the existing code might work properly.
An abstract class can have fields and constants defined

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

12 static
Use the static modifier to declare a static member, which belongs 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 referenced through the type name.

13 Access Modifiers
Modifier Public Description There are no restrictions on accessing public members. Access is limited to within the class definition. This is the default access modifier type if none is formally specified Access is limited to within the class definition and any class that inherits from the class Access is limited exclusively to classes defined within the current project assembly Access is limited to the current assembly and types derived from the containing class. All members in current project and all members in derived class can access the

Private

Protected

Internal

protected internal

Santosh – C#.NET Interview Preparation

Page 14

Santosh .NET Training variables.

14 Arrays and Collection of Objects
14.1 Arrays
Arrays are collections of data. You can use it like any other variable but inside it contains more than 1 value (a collection of data). You can access the data from array variable using 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’ll use to access a specific element of array. The array elements are 0 based. Arrays are of fixed size.

14.2 Arrays of Objects
Just like we use Arrays to work with value types like int and string they can also be used to work with Custom types. There are disadvantages 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 this 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 size mentioned 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 would initialize an ArrayList.

Santosh – C#.NET Interview Preparation

Page 15

Santosh .NET Training

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 the ArrayList here. Using the ArrayList, You can add and remove any number of items dynamically. The advantages of using ArrayList over Array are 1. 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).
Santosh – C#.NET Interview Preparation Page 16

Santosh .NET Training 1. You can easily remove or add the objects dynamically. 1. You can insert items at a specific position. The disadvantages of ArrayList 1. 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 any type of the custom objects because you have to cast the items.

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

T means any Type.

15 Association of the Objects
There are two basic types of associations (relationships). 1. Aggregation 1. Containment/Composition

15.1 Aggregation
Aggregation is the (*the *) relationship between two classes. When object of one class has an (* has *) object of another, then we called that there is an aggregation between two classes.

15.2 Containment/Composition
Defining a class with in a class is called containment.

16 Value Types
The value types consist of two main categories:
Structs Enumerations Structs fall into these categories: Numeric types o Integral types o Floating-point types Santosh – C#.NET Interview Preparation Page 17

Santosh .NET Training
o decimal bool User 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 differs from the assignment of reference type variables, which copies a reference to the object but 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, the nullable types feature does allow for values types to be assigned to null. o Nullable types are instances of the System.Nullable<T> struct. A nullable type can represent the correct range of values for its underlying value type, plus an additional null value. For example, a Nullable<Int32>, pronounced "Nullable of Int32," can be assigned any value from -2147483648 to 2147483647, or it can be 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 Default Values Table.

16.2 Value vs. Reference Type
With value types: Value type assignments copy all me mbers 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/prope rties copy whole value - this behavior is the same as value assignment. Value types assigned to an object are boxed – that is, they are surrounded by an object 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 an enclosing 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 class are 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 members defaulted. In contrast, with reference types:

Santosh – C#.NET Interview Preparation

Page 18

Santosh .NET Training Reference type assignment only copies the reference - this decrements/increments reference counts as appropriate. Reference types passed by parameter or returned fro m methods/properties pass a reference - the reference is copied, but both references refer to the same original object. Reference types are only destroyed whe n garbage collected - after all references to the object are determined to be unreachable. Reference types are generally on the heap - it’s always possible compiler may optimize, but in general you should always think of them as heap objects Reference types can be null - default value of members that are reference types members is null.

16.3 struct
A struct type is a value type that is typically used to encapsulate small groups of related variables. 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 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.

16.4 Structs Vs Classes

Feature Is a reference type? Is a value type? Can have nested Types (enum, class, struct)? Can have constants? Can have fields?

Struct Class No Yes* Yes No Yes Yes Yes Yes* Yes Yes

Notes

Struct instance fields cannot be initialized, will automatically
Page 19

Santosh – C#.NET Interview Preparation

Santosh .NET Training initialize to default value. Can have Can have Can have Can have prope rties? indexers methods? events? Yes Yes Yes Yes* Yes Yes Yes Yes

Structs, like classes, can have events, but care must be taken that you don’t subscribe to a copy of a struct instead of the struct you intended.

Can have static me mbers (constructors, fields, methods, properties, etc.)? Can inherit?

Yes

Yes

No*

Yes*

Classes can inherit from other classes (or object by default). Structs always inherit from System.ValueType and are sealed implicitly Struct overload of constructor does not hide default constructor. The struct default constructor initializes all instance fields to default values and cannot be changed.

Can implement interfaces? Can ove rload constructor?

Yes Yes*

Yes Yes

Can define default constructor?

No

Yes

Can ove rload operators? Can be generic? Can be partial? Can be sealed?

Yes Yes Yes Always*

Yes Yes Yes Yes

Can be referenced in instance me mbers using this keyword?

Yes*

Yes

Needs new operator to create instance?
Santosh – C#.NET Interview Preparation

No*

Yes

Structs are always sealed and can never be inherited from. In structs, this is a value variable, in classes, it is a readonly reference. C# classes must be instantiated using new. However, structs do
Page 20

Santosh .NET Training not require this. While new can be used on a struct to call a constructor, you can elect not to use new and init the fields yourself, but you must init all fields and the fields must be public!

17 Constants
Constants are immutable (changeless) values which are known at compile time and do not 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 so me cases, implicit conversions are allowed. 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 type implemented 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. Santosh – C#.NET Interview Preparation Page 21

Santosh .NET Training
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 initializers
These let you assign values to any accessible fields or properties of an object at creation time without having to explicitly invoke a constructor. The following example shows how 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 initializers
These let you specify one or more element intializers, when you initialize a collection class that implements IEnumerable. The element initializers can be a simple value, an expression or an object initializer. By using a collection initializer you do not have to specify 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 Cat class defined in a previous example. Note that the individual object initializers are enclosed in braces and separated by commas.
List<Cat> cats { new Cat(){ new Cat(){ new Cat(){ }; = new List<Cat> Name = "Sylvester", Age=8 }, Name = "Whiskers", Age=2 }, 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 };

Santosh – C#.NET Interview Preparation

Page 22

Sponsor Documents

Or use your account on DocShare.tips

Hide

Forgot your password?

Or register your new account on DocShare.tips

Hide

Lost your password? Please enter your email address. You will receive a link to create a new password.

Back to log-in

Close