Skip to content

Latest commit

 

History

History
1992 lines (1574 loc) · 106 KB

File metadata and controls

1992 lines (1574 loc) · 106 KB
 C# Programming Language- CsharpChecklist

Sno. Topic 1 About C# Programming Language like history and type and purpose and features? What is OOPS? 2 What is .NET Framework ? What are compilers ? Difference between Compiler and Interpreter ? 3 Classes in C# ? Class name Conventions ? Types of classes like partial , non static and static ? 4 Escape Sequences? 5 Basic Structure of C# Program like Main( ) Method usage ? Explaining Commad Line Arguments . 6 What are namespaces ? 7 What is the difference between classes and namespaces? 8 What is the process of compiling of C# source code ? Explaining CLR , CLS and CTS ? Explaining Language Interoperability ? 9 reading and Writing the text files by using FileStream class,StreamReader and StreamWriter. 10 What is JIT Compiler ? 11 What is Assembly ? Types of Assembly ? 12 What is Object ? 13 What is the base class of all classes in the .NET Framework? 14 Explain the .NET Architecture ? 15 Latest .NET Framework and Latest C# languages ? How many .Net based languages available ? 16 What are Variables? Variable Naming Conventions ? Declaring and Initializing Variables ? 17 What are Data Types ? Types of Data types ? 18 Difference between Value type and reference type data types? 19 Difference between dynamic and var type variables ? 20 Difference between variables and constants ? 21 Difference between constants and read only fields? 22 Console.ReadLine() and Console.WriteLine() Functionality ? 23 What is using Keyword ? 24 What are comments in C# ? Types of Comments ? 25 Instantiating Class and its process? 26 What are operators and Operands ? Types of Operators ? Conversions and Castings ? Boxing and Unboxing ? 27 Explain Arithmetic , Arithmetic assignment , Unary , Comparison and Logical Operators ? 28 Explaining Conditional Constructs like if-else , nested if-else and switch case ? 29 Explain Loops like While , do while , For loop and foreach loop ? 30 Explaining Jump Statemenst like Goto , break ,continue statement as well as return keyword . 31 What are the class members ? 32 What are access specifiers ? How may access specifiers are there ? 33 What are methods and convention for methods naming? 34 Explain the importance of Parameterized Methods ? 35 Explain call by value , call by reference and call by output ? 36 Explain Optional and Named Arguments ? 37 Explain Recursion ? And it's advantages? 38 Explain static attributes,static methods and static class? 39 Explaining Constructors ? Types of Constructors like static,private and instance ? Constructors with parameter ? 40 Explaining Destructors ? 41 Explain the Garbage Collection and it's Process and working ? 42 Explain the Finalize() and Dispose() methods in Garbage Collection class? 43 Explain Properties in C#? 44 Explaining Structure ? Difference between Structure and Class? 45 Explaining Enumerations and it's usage with examples? 46 Explaining Array and it's Implementation in one dimensional and two dimensional ? Copying array ? 47 Explain the Param Arrays and Jagged Array? Passing array as parameters ? Passing array by ref keyword ? 48 Explaining Array Class with it's properties like Length,Rank etc and also methods like Sort, Clear and GetLength ? 49 Explain the Collections ? 50 Explain the Generic Class in C# ? Advantage of Generic Class? 51 Explain the types of Collections like generic and non generic ? 52 Explain the working of ArrayList , List,Stack,Queue and Dictionary collections with generic and non generic ? 53 Explain Inheritance and implementation ? 54 Explain abstract class and abstract methods ? 55 Explain the sealed classes? 56 Explain the interfaces ? 57 Explain base class initialization ? 58 What is Polymorphism? 59 Implementing function overloading, operator overloading and constructor overloading ? 60 Implementing function overriding ? 61 Reading and writing the text file by using File class? 62 Reading and Writing the text files by using FileStream class,StreamReader and StreamWriter. 63 Creating Directory and Creating files by using DirectoryInfo and FileInfo classes. 64 Fetching Directory and File details by using DirectoryInfo and FileInfo classes. 65 Exception handling by using try,catch and finally . 66 System Exceptions and Application Exceptions handling . 67 Creating application exception and throwing it. 68 Threads in C# like single thread and multi thread ? 69 Creating single thread and multi thread ? 70 Implementing Thread methods like Start(),Sleep(0,Abort() . 71 What is Thread Life Cycle ? 72 Synchronizing threads ? 73 Explaining Delegates ? Types of Delegates ? 74 Working with Events in C#? 75 What are attribute and reflections in C#? Task 1.1

1.Explain the difference between .NET Platform,.NET Framework and C# language . 2.Explain the role of compilers ? 3.Explain the role of CLR and it's components ? 4.What do you know by namespaces , explain with examples. 5.Write the program to display the below output :

-------------------------------------Company------------------------------ Total Employee :550 .NET Employee :100 PHP Employee :150 Address :NSEZ -----------------------------------For more info visit us on www.xyz.com-----------

6.What is the difference between value type and reference type, explain with examples? 7.Explain the difference between variable and constants? 8.Explain the type of comments available in C#? 9.Expain the System namespace with examples? 10.Write the code to display your time table like in the below format :

--------------------------------------------------TIME TABLE------------------------------------------------------ | Time Activity | 7AM Getting UP | 8AM Breakfast | -- -------- | -- -------- | -- -------- | | | | | |

task1.1 q1

.net framework-- you build code using .net framework it runs only on windows operating system it is not open source it has various languages in it. libraries written in programming lang. to reduce your work in implementing already implemented it is a complete envirnment that allow developers to develop,run and deploy the application.

.net platform-- the code runs on .net platform. it is used to create apps,websites and services on any device and os

c# object oriented programming language developed by microsoft

q2

a compiler is a computer program that transforms source code into another language(object code)

q3

clr provides runtime environment in .net

q4- a namespace is a coontainer which contains classes,structures,interfaces,enumerations etc.eg.system.io groups i/p o/p related features and it allows code to create a system to organize your code. e.g- using System; namespace MyNameSpace { namespace Video{ class MyVideo{ public static void play(){ }}} namespace Audio{ same as video

}}

q5- reference type stores in heap contains pointer to another memory allocatione. e.g are classes,object,arrays,indexers,interfaces. int[] iArray=new int[20];

value type stored in stack holds data within its own memory allocation e.g int x=10;

q8- 3 types of comment in c# single line // multiline /* .. */ xmlcomments ///

q9-- system namespace contains fundamental classes and base classes that define commonly used value and reference data types,events and events handlers,interfaces ,attributes and processing exceptions.

enum - The enum keyword is used to declare an enumeration, a distinct type that consists of a set of named constants called the enumerator list. Usually it is best to define an enum directly within a namespace so that all classes in the namespace can access it with equal convenience Enums are strongly typed constants. 1.Enums are enumerations. 2. Enums are strongly typed constants. Hence, an explicit cast is needed to convert from enum type to an integral type and vice versa. Also, an enum of one type cannot be implicitly assigned to an enum of another type even though the underlying value of their members are the same. 3. The default underlying type of an enum is int. 4. The default value for first element is ZERO and gets incremented by 1. 5. It is possible to customize the underlying type and values. 6. Enums are value types. 7. Enum keyowrd (all small letteres) is used to create enumerations, where as Enum class, contains static GetValues() and GetNames() methods which can be used to list Enum underlying type values and Names.

Structure 1-Structure is a value type that is why its object is created on the stack memory. 2-Structure does not support the inheritance. 3-Structure can only have the parametrized constructor. it means a structure can not have the non-parametrized constructor,default constructor and destructor also. 4-The member variable of structure can not be initialized directly. 5-Structure object can be created without using the new keyword.(optional)

foreach //The foreach loop in C# executes a block of code on each element in an array or a collection of items. //When executing foreach loop it traversing items in a collection or an array . //The foreach loop is useful for traversing each items in an array or a collection of items and displayed one by one.

//a do while loop is a control flow statement that executes a block of code at least once, and then repeatedly executes the block, or not, //depending on a given boolean condition at the end of the block.

A while loop statement in C# repeatedly executes a target statement as long as a given condition is true.

method hiding or new keyword- The "override" modifier extends the base class method, and the "new" modifier hides it. The "virtual" keyword modifies a method, property, indexer, or event declared in the base class and allows it to be overridden in the derived class. The "override" keyword extends or modifies a virtual/abstract method, property, indexer, or event of the base class into the derived class. The "new" keyword is used to hide a method, property, indexer, or event of the base class into the derived class. If a method is not overriding the derived method then it is hiding it. A hiding method must be declared using the new keyword

In base class method is declared as virtual In derived class we override the same method. The virtual keyword indicates that method can be overridden in any derived class. – Runtime polymorphism is done using inheritance and virtual functions. Method overriding is called runtime polymorphism. It is also called late binding. When overriding a method, you change the behavior of the method for the derived class. Compile time polymorphism is method and operators overloading. It is also called early binding. In method overloading method performs the different task at the different input parameters.

— polymorphism-one interface, multiple functions In static polymorphism, the response to a function is determined at the compile time. In dynamic polymorphism, it is decided at run-time. The mechanism of linking a function with an object during compile time is called early binding. It is also called static binding. C# provides two techniques to implement static polymorphism. They are: 1-Method overloading Overloading a method simply involves having another method with the same prototype. 2-Operator overloading It means that we are defining an operator for a class. If you want to compare two objects with by data values instead of by reference, you'll want to overload . There are some places where mostly operators overloading are used. Mathematical or Physical modeling Graphical programs Text manipulations Financial programs etc. Operators Description +, -, !, ~, ++, -- These unary operators take one operand and can be overloaded. +, -, *, /, % These binary operators take one operand and can be overloaded. ==, !=, <, >, <=, >= The comparison operators can be overloaded &&, || The conditional logical operators cannot be overloaded directly. +=, -=, *=, /=, %= The assignment operators cannot be overloaded. =, ., ?:, ->,new, is, sizeof, typeof These operators cannot be overloaded.

Advantages generics- It helps you to maximize code reuse, type safety, and performance. You can create generic collection classes. The .NET Framework class library contains several new generic collection classes in the System.Collections.Generic namespace. You may use these generic collection classes instead of the collection classes in the System.Collections namespace. You can create your own generic interfaces, classes, methods, events, and delegates. You may create generic classes constrained to enable access to methods on particular data types. You may get information on the types used in a generic data type at run-time by means of reflection. Generic class is a class whose objects each can operate on different type of data.

anonymous - A variable, declared outside the anonymous method can be accessed inside the anonymous method. A variable, declared inside the anonymous method can’t be accessed outside the anonymous method. We use anonymous method in event handling. An anonymous method, declared without parenthesis can be assigned to a delegate with any signature. Unsafe code can’t be accessed within an anonymous method. An anonymous method can’t access the ref or out parameters of an outer scope.

delegate - A delegate in C# is similar to a function pointer in C or C++. Using a delegate allows the programmer to encapsulate a reference to a method inside a delegate object. The delegate object can then be passed to code which can call the referenced method, without having to know at compile time which method will be invoked. Unlike function pointers in C or C++, delegates are object-oriented, type-safe, and secure. It is used to create method objects. With the Invoke method we can call a delegate as a method. Delegates are useful when: A single method is being called. A class may want to have multiple implementations of the method specification. It is desirable to allow using a static method to implement the specification. An event-like design pattern is desired (for more information, see the Events Tutorial). The caller has no need to know or obtain the object that the method is defined on. The provider of the implementation wants to "hand out" the implementation of the specification to only a few select components. Easy composition is desired.

Constructor- A special method of the class that will be automatically invoked when an instance of the class is created is called a constructor. The main use of constructors is to initialize private fields of the class while creating an instance for the class. When you have not created a constructor in the class, the compiler will automatically create a default constructor in the class. The default constructor initializes all numeric fields in the class to zero and all string and object fields to null.

Some of the key points regarding the Constructor are: 1-A class can have any number of constructors. 2-A constructor doesn't have any return type, not even void. 3-A static constructor can not be a parametrized constructor. 4-Within a class you can create only one static constructor.

Constructors can be divided into 5 types: 1-Default Constructor 2-Parametrized Constructor 3-Copy Constructor 4-Static Constructor 5-Private Constructor

Default Constructor A constructor without any parameters is called a default constructor; in other words this type of constructor does not take parameters. The drawback of a default constructor is that every instance of the class will be initialized to the same values and it is not possible to initialize each instance of the class to different values. The default constructor initializes: All numeric fields in the class to zero. All string and object fields to null.

Destructor in c#- Destructors are invoked automatically, and cannot be invoked explicitly. Destructors cannot be overloaded. Thus, a class can have, at most, one destructor. Destructors are not inherited. Thus, a class has no destructors other than the one, which may be declared in it. Destructors cannot be used with structs. They are only used with classes. An instance becomes eligible for destruction when it is no longer possible for any code to use the instance. Execution of the destructor for the instance may occur at any time after the instance becomes eligible for destruction. When an instance is destructed, the destructors in its inheritance chain are called, in order, from most derived to least derived. Destructors are used to destruct instances of classes.
In C# you can never call them, the reason is one cannot destroy an object. So who has the control over the destructor (in C#)? it's the .NET frameworks Garbage Collector (GC).

Syntax of Destructor(~)

~ ClassName()

Characteristics of Destructor Destructors () cannot be defined in Structs. Destructors () are only used with classes. Destructor cannot be inherited or overloaded. Destructor does not take modifiers or have parameters. Destructor cannot be called. They are invoked automatically. An instance becomes eligible for destruction when it is no longer possible for any code to use the instance. The Programmer has no control over when destructor is called because this is determined by Garbage Collector. Destructor is called when program exits. Execution of the destructor for the instance may occur at any time after the instance becomes eligible for destruction. Destructor implicitly calls Finalize on the base class of object. Parameterized Constructor A constructor with at least one parameter is called a parametrized constructor. The advantage of a parametrized constructor is that you can initialize each instance of the class to different values.

Private Constructor When a constructor is created with a private specifier, it is not possible for other classes to derive from this class,neither is it possible to create an instance of this class. They are usually used in classes that contain static members only. Some key points of a private constructor are: One use of a private constructor is when we have only static members. It provides an implementation of a singleton class pattern Once we provide a constructor that is either private or public or any, the compiler will not add the parameter-less public constructor to the class.

Static Constructor When a constructor is created as static, it will be invoked only once for all of instances of the class and it is invoked during the creation of the first instance of the class or the first reference to a static member in the class. A static constructor is used to initialize static fields of the class and to write the code that needs to be executed only once. A static constructor is used to initialize any static data, or to perform a particular action that needs performed once only. A static constructor does not take access modifiers or have parameters. A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced. A static constructor cannot be called directly. Static constructor will not accept any parameters because it is automatically called by CLR. The user has no control on when the static constructor is executed in the program. A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file. Static constructor is called only once before first instance of the class is created. It runs irrespective of the instantiation being done by parameterized or parameterless constructor

Dictionary A Dictionary class is a data structure that represents a collection of keys and values pair of data. The key is identical in a key-value pair and it can have at most one value in the dictionary, but a value can be associated with many different keys. Hashtable The Hashtable class represents a collection of key-and-value pairs that are organized based on the hash code of the key. It uses the key to access the elements in the collection. SortedList - The SortedList class represents a collection of key-and-value pairs that are sorted by the keys and are accessible by key and by index. A sorted list is a combination of an array and a hash table. It contains a list of items that can be accessed using a key or an index. If you access items using an index, it is an ArrayList, and if you access items using a key, it is a Hashtable. The collection of items is always sorted by the key value.

basics C# is a general-purpose, object-oriented programming language.Its development team is led by Anders Hejlsberg. The most recent version is C# 7.0 which was released in 2017 along with Visual Studio 2017 Purpose of Main() method - Main method is the entry point into your application. C# is case sensitive language. Datatypes in c#- 1.Boolean type – Only true or false . 2.Integral Types - sbyte, byte, short, ushort, int, uint, long, ulong, char 3.Floating Types – float and double 4.Decimal Types 5.String Type
Verbatim Literal- Verbatim Literal is a string with an @ symbol prefix, as in @“Hello”. Verbatim literals make escape sequences translate as normal printable characters to enhance readability. Example: Without Verbatim Literal : "C:\Pragim\DotNet\Training\Csharp"; // Less Readable With Verbatim Literal : @"C:\Pragim\DotNet\Training\Csharp"; // Better Readable

Operators in c#- Assignment Operator = Arithmetic Operators like +,-,*,/,% Comparison Operators like ==, !=,>, >=, <, <= Conditional Operators like &&, || Ternary Operator ?: Unary operator-+, -, !, ~, ++, --, Null Coalescing Operator ??

Value Types - int, float, double, structs, enums etc Reference Types – Interface, Class, delegates, arrays etc By default value types are non nullable. To make them nullable use ? int i = 0 (i is non nullable, so "i" cannot be set to null, i = null will generate compiler error) int? j = 0 (j is nullable int, so j=null is legal) Nullable types bridge the differences between C# types and Database types.

Implicit conversion is done by the compiler:

  1. When there is no loss of information if the conversion is done
  2. If there is no possibility of throwing exceptions during the conversion Example: Converting an int to a float will not loose any data and no exception will be thrown, hence an implicit conversion can be done. Where as when converting a float to an int, we loose the fractional part and also a possibility of overflow exception. Hence, in this case an explicit conversion is required. For explicit conversion we can use cast operator or the convert class in c#.

Difference between Parse and TryParse

  1. If the number is in a string format you have 2 options - Parse() and TryParse()
  2. Parse() method throws an exception if it cannot parse the value, whereas TryParse() returns a bool indicating whether it succeeded or failed.
  3. Use Parse() if you are sure the value will be valid, otherwise use TryParse()

Comments are used to document what the program does and what specific blocks or lines of code do. C# compiler ignores comments. Single line Comments - // Multi line Comments - /* */ XML Documentation Comments - ///

In general classes, structs, enums, interfaces, delegates are called as types and fields, properties, constructors, methods etc., that normally reside in a type are called as type members. Type members can have all the access modifiers, where as types can have only 2 (internal, public) of the 5 access modifiers

Jit Compiler-

  1. The JIT compiler translates the MSIL code of an assembly to native code and uses the CPU architecture of the target machine to execute a .NET application.
  2. It also stores the resulting native code so that it is accessible for subsequent calls.
  3. If a code executing on a target machine calls a non-native method, the JIT compiler converts the MSIL of that method into native code.
  4. The JIT compiler also enforces type-safety in the runtime environment of the .NET Framework.
  5. It checks for the values that are passed to parameters of any method.

What is a .Net Assembly? The .NET assembly is the standard for components developed with the Microsoft.NET. Dot NET assemblies may or may not be executable, i.e., they might exist as the executable (.exe) file or dynamic link library (DLL) file. +All the .NET assemblies contain the definition of types, versioning information for the type, meta-data, and manifest. The designers of .NET have worked a lot on the component (assembly) resolution. There are two kind of assemblies in .NET; • private • shared Private assemblies are simple and copied with each calling assemblies in the calling assemblies folder. Shared assemblies (also called strong named assemblies) are copied to a single location (usually the Global assembly cache).

What is the base class of all classes in the .NET Framework? System.Object-it is base class Every Type inherits from Object Type, directly or indirectly, and therefore has access to its members.
Here’s a brief summary of all members of System.Object :

• Object constructor – called when object is created, ultimately called for every object • Equals(object) – compares object to specified object; true for reference types if parameter references the current object [virtual] • Equals(object,object) – static method to compare two objects • Finalize – called when the object is being destroyed [virtual] • GetHashCode – is meant to provide a unique number used in hashing algorithms, but should be overridden so that value returned is unique based on object contents [virtual] • GetType – returns the Type of the object • ReferenceEquals(object,object) – static method to see if two references refer to the same object • ToString – returns a string that describes the object; by default, just returns • the type name

Using keyword- using System; using is the directive used to include the namespace in the program and System is the name of namespace.

Goto stmt- The goto statement is a jump statement that controls the execution of the program to another segment of the same program. You create label at anywhere in program then can pass the execution control via the goto statements. Break stmt- When the break statement is encountered inside a loop, the loop is immediately terminated and program control resumes at the next statement

Continue stmt- A Continue statement jumps out of the current loop condition and jumps back to the starting of the loop code.

The basic difference between generic and non-generic collections:

  • Non-Generic collections - These are the collections that can hold elements of different data types. It holds all elements as object type. So it includes overhead of type conversions.

  • Generic collections - These are the collections that can hold data of same type and we can decide what type of data that collections can hold.

Some advantages of generic collections - Type Safe, Secure, reduced overhead of type conversions.

  1. What is C#? C# is a simple, modern, general purpose programming language. It is an object oriented programming language developed by Microsoft. It is a safe and managed language that is compiled by .NET framework to generate Microsoft intermediate language (machine code).

  2. What is the reason behind the invention of C#? C# is designed for Common Language Infrastructure (CLI). It contains the executable code and runtime environment that makes the users able to use various high-level languages on different computer platforms and architectures.

  3. What are the main reasons to use C# language? These are top reasons to use C# language: Easy to learn General purpose and object oriented programming language Component oriented Structured language Can be compiled on variety of computer platforms Produces efficient programs Part of .net framework

  4. What is the difference between public, static and void? You can access public declared variables anywhere in the application. Static declared variables are globally accessible without creating an instance of the class. Void is a type modifier that specifies that the method doesn't return any value.

  5. What are constructors in C#? A constructor is a member function in the class and has the same name as its class. Whenever the object class is created, the constructor is automatically invoked. It constructs the value of data members while initializing the class.

  6. What are the different types of constructors in C#? Basically, there are five types of constructors: Static constructor Private constructor Copy constructor Default constructor Parameterized constructor

  7. What is static constructor? Static constructor is used to initialize static data members as soon as the class is referenced first time.

  8. What is method overloading in C#? Method overloading is mechanism to create multiple methods with the same name and unique signature in the same class. When you go for compilation, the compiler uses overload resolution to determine the specific method to be invoked.

  9. Is overriding of a function possible in the same class? No

  10. What is array? Array is a set of related instances either value or reference types. There are three types of array supported by C#: Single Dimensional Array: It contains a single row. It is also known as vector array. Multi Dimensional Array: It is rectangular and contains rows and columns. Jagged Array: It also contains rows and columns but it has an irregular shape.

  11. What is ArrayList? ArrayList is a dynamic array. You can add and remove the elements from an ArrayList at runtime. In the ArrayList, elements are not automatically sorted.

  12. What is a collection? A collection works as a container for instances of other classes. All classes implement ICollection interface.

  13. What is an interface? Interface is an abstract class that has only public abstract method. These methods only have declaration not the definition. These abstract methods must be implemented in the inherited classes.

  14. What is the lock statement in C#? Lock statement is used to ensure that one thread doesn?t enter a critical section of code while another thread is in the critical section. If another thread attempts to enter a locked code it will wait, block, until the object is released.

  15. What is serialization? If you want to transport an object through network then you have to convert the object into a stream of bytes. The process of converting an object into a stream of bytes is called serialization.

  16. How to declare a property in a class? int m_PersonID = 0;
    public int PersonID
    {
    get { return m_PersonID; }
    set { m_PersonID = value; }
    }

  17. What is the difference between early binding and late binding in C#? Early binding and late binding are the concept of polymorphism. There are two types of polymorphism in C#. Compile Time Polymorphism: It is also known as early binding. Run Time Polymorphism: It is also known as late binding or method overriding or dynamic polymorphism.

  18. Which are the access modifiers available in C#? Following are the access modifiers generally used for accessibility: Public: If you define an attribute or method as public, it can be accessed from any code of the project. Private: A private defined attribute or method can be accessed by any code within the containing class only. Protected: If you define the method or attribute as protected it can be accessed by any method in the inherited classes and any method within the same class. Internal: If you define an attribute or a method as internal, it is restricted to classes within the current position assembly. Protected internal: If you define an attribute or method as protected internal, access is restricted to classes within the current project assembly or types derived from the containing class.

  19. What is the difference between abstract class and interface in C#? Abstract class can have abstract and concrete methods whereas interface has only abstract methods.

  20. What is the difference between dispose() and finalize() methods in C#? The dispose() method is explicitly called by user to free unmanaged resources such as files, database connections etc whereas finalize() method is implicitly called by garbage collector to free unmanaged resources like files, database connections etc. The dispose() method belongs to IDisposable interface whereas finalize() method belongs the Object class.

  21. What is the difference between method overloading and method overriding in C#? Method parameters must be different in method overloading whereas it must be same in method overriding. Inheritance is not required in method overloading, it occurs within the same class. But inheritance is required in method overriding.

  22. What is object pool in .Net? Object pool is a container of ready to use objects. It reduces the overhead of creating new object.

  23. What is delegate in C#? A delegate in C# is an object that holds the reference to a method. It is like function pointer in C++.

  24. What is Hashtable? A Hashtable is a collection of key/value pairs. It contains values based on the key.

  25. What is Reflection? Reflection allows us to get metadata and assemblies of an object at runtime.

  26. What is Garbage Collection? Garbage Collection is a process of releasing memory automatically occupied by objects which are no longer accessible

Difference between ref and out Keyword- [ref] means that the parameter has a value on it before going into the function. [out] means that the parameter has no official value before going into the function.

Static and instance Class members- Static members are invoked using class name while instance members are invoked using object. Example- class Test { int x; static int y; void F() { x = 1; // Ok, same as this.x = 1 y = 1; // Ok, same as Test.y = 1 } static void G() { x = 1; // Error, cannot access this.x y = 1; // Ok, same as Test.y = 1 } static void Main() { Test t = new Test(); t.x = 1; // Ok t.y = 1; // Error, cannot access static member through instance Test.x = 1; // Error, cannot access instance member through type Test.y = 1; // Ok } }

Method overriding vs method hiding For hiding the base class method from derived class simply declare the derived class method with the new keyword. Whereas in C#, for overriding the base class method in a derived class, you need to declare the base class method as virtual and the derived class method as overriden. New is reference-type specific, overriding is object-type specific.

Why Properties or What is the need for encapsulation – In Properties, we use predefined Set or Get method. Marking the class field public & exposing is risky, as you will not have control what gets assigned & returned. To understand this clearly with an example lets take a student class who have an ID, pass mark, name. Now in this example some problem with a public field The ID should not be -ve. Name can not be set to null A pass mark should be read-only. If student name is missing No Name should be returned. To remove this problem We use Get and set method. // A simple example public class student { public int ID; public int passmark; public string name; public class programme { public static void main() { student s1 = new student(); s1.ID = -101; // here ID can't be -ve s1.Name = null ; // here Name can't be null } }

Now we take an example of get and set method

public class student { private int _ID; private int _passmark; private string_name ; // for id property public void SetID(int ID) { if(ID<=0) { throw new exception("student ID should be greater then 0"); } this._ID = ID; } public int getID() { return_ID; } } public class programme { public static void main() { student s1 = new student (); s1.SetID(101); } // Like this we also can use for Name property public void SetName(string Name) { if(string.IsNullOrEmpty(Name)) { throw new exeception("name can not be null"); } this._Name = Name; } public string GetName() { if( string.IsNullOrEmpty(This.Name)) { return "No Name"; } else { return this._name; } // Like this we also can use for Passmark property public int Getpassmark() { return this._passmark; } }

Struct vs class A struct is a value type where as a class is a reference type. All the differences that are applicable to value types and reference types are also applicable to classes and structs. Structs are stored on stack, where as classes are stored on the heap. Value types hold their value in memory where they are declared, but reference types hold a reference to an object in memory. Value types are destroyed immediately after the scope is lost, where as for reference types only the reference variable is destroyed after the scope is lost. The object is later destroyed by garbage collector. (We will talk about this in the garbage collection session) When you copy a struct into another struct, a new copy of that struct gets created and modifications on one struct will not affect the values contained by the other struct When you copy a class into another class, we only get a copy of the reference variable. Both the reference variables point to the same object on the heap. So, operations on one variable will affect the values contained by the other reference variable.

Structs can't have destructors, but classes can have destructors. Structs cannot have explicit parameter less constructor where as a class can. Struct can't inherit from another class where as a class can, Both structs and classes can inherit from an interface. Examples of structs in the .NET Framework-int (System.Int32), double(System.Double) etc. Note 1: A class or a struct cannot inherit from another struct. Struct are sealed types. Note 2: How do you prevent a class from being inherited? Or What is the significance of sealed keyword?

              Compiler	                                            Interpreter

1 Compiler Takes Entire program as input Interpreter Takes Single instruction as input . 2 Intermediate Object Code is Generated No Intermediate Object Code is Generated 3 Conditional Control Statements are Executes faster Conditional Control Statements are Executes slower 4 Memory Requirement : More (Since Object Code is Generated) Memory Requirement is Less 5 Program need not be compiled every time Every time higher level program is converted into lower level program 6 Errors are displayed after entire program is checked Errors are displayed for every instruction interpreted (if any) 7 Example : C Compiler Example : BASIC

Escape Sequences- These are basically the special characters or escape characters. The backslash character () in a regular expression indicates that the character that follows it either is a special character or should be interpreted literally.

Command-Line Arguments Main() method is where program starts execution. Main method doesn’t accept parameter from any method. It accept parameter through command line. It is an array type parameter that can accept n number of parameter in runtime. The Main method can be declared with or without a string[] parameter that contains command-line arguments. Basically main method can have two Signatures. static void Main(string[] args) or static int Main(string[] args) In which string[] args will store whatever we have passed through command line to our application. 0th element in args array will hold Application Name it Self. Suppose our application's name is printname.exe that prints the names on screen when passed by command line like below command in cmd.exe printname.exe kirtan suresh chirag it will print printname kirtan suresh chirag

namespaces vs class- Namespace: A category or brand of cars. Note that the brand really doesn't have to dictate how the car is built. You can't say a Honda always have four doors,.. A namespace is used to group classes into a logical set.Multiple classes can exist in the same namespace. Class: Blueprint for how to build a specific car.

Exception Handling An exception is an unforeseen error that occurs when a program is running. Trying to read from a file that does not exist, throws FileNotFoundException. Trying to read from a database table that does not exist, throws a SqlException. Showing actual unhandled exceptions to the end user is bad for two reasons

  1. Users will be annoyed as they are cryptic and does not make much sense to the end users.
  2. Exceptions contain information, that can be used for hacking into your application An exception is actually a class that derives from System.Exception class. The System.Exception class has several useful properties, that provide valuable information about the exception. Message: Gets a message that describes the current exception Stack Trace: Provides the call stack to the line number in the method where the exception occurred.

We use try, catch and finally blocks for exception handling. try - The code that can possibly cause an exception will be in the try block. catch - Handles the exception. finally - Clean and free resources that the class was holding onto during the program execution.

Specific exceptions will be caught before the base general exception, so specific exception blocks should always be on top of the base exception block. Otherwise, you will encounter a compiler error. Note: It is a good practice to always release resources in the finally block, because finally block is guarenteed to execute, irrespective of whether there is an exception or not. The InnerException property returns the Exception instance that caused the current exception. To look at the inner exception, you have to make this program cuase an exception fail. To do that you have 3 options

  1. Enter a Character instead of a number (Causes Format Exception)
  2. Or Enter a very big number that an interger cannot hold (Causes Over Flow Exception)
  3. Or Enter Zero for Second Number (Causes Divide By Zero Exception When do you usually go for creating your own custom exceptions? If none of the already existing dotnet exceptions adequately describes the problem.

Consider that

  1. I have an asp.net web application.
  2. The application should allow the user to have only one logged in session.
  3. If the user is already logged in, and if he opens another browser window and tries to login again, the application should throw an error stating he is already logged in another browser window. With in the .NET framework we donot have any exception, that adequately describes this problem. So this scenario is one of the examples where you want to create a custom exception. We know that an exception is a class. So to create a Custom exception,

Exceptions are unforeseen errors that occur when a program is running. For example, when an application is executing a query, the database connection is lost. Exception handling is generally used to handle these scenarios. But many a times I have seen programmers using exception handling to implement programming logic which is bad, and this is called as exception handling abuse. Program using exception handling to implement logical flow:

Indexers - Indexers which are used for treating an object as an array. Indexers are always created with this keyword. Parameterized property are called indexer. Indexers are implemented through get and set accessors for the [ ] operator. ref and out parameter modifiers are not permitted in indexer. The formal parameter list of an indexer corresponds to that of a method and at least one parameter should be specified. Indexer is an instance member so can't be static but property can be static. Indexers are used on group of elements. Indexer is identified by its signature where as a property is identified it's name. Indexers are accessed using indexes where as properties are accessed by names. Indexer can be overloaded.

multithreading- Threads allow you to develop more efficient applications synchronizing through the shared memory.

  1. Process - Process is what the operating system uses to facilitate the execution of a program by providing the resources required. Each process has a unique process Id associated with it. You can view the process within which a program is being executed using windows task manager.
  2. Thread - Thread is a light weight process. A process has at least one thread which is commonly called as main thread which actually executes the application code. A single process can have multiple threads.

All the threading related classes are present in System.Threading namespace. Advantages of multithreading:

  1. To maintain a responsive user interface
  2. To make efficient use of processor time while waiting for I/O operations to complete.
  3. To split large, CPU-bound tasks to be processed simultaneously on a machine that has multiple CPUs/cores.

Disadvantages of multithreading:

  1. On a single-core/processor machine threading can affect performance negatively as there is overhead involved with context-switching.
  2. Have to write more lines of code to accomplish the same task.
  3. Multithreaded applications are difficult to write, understand, debug and maintain. Why we should not use threads in our applications?

Creating and destroying a thread is costly process it takes processor time. Several things must be performed while creating

  1. Operating system must go in to kernel mode.
  2. Other threads must notify the new thread is created.
  3. Operating system must leave the kernel mode. Etc.

From the developers point of view

  1. Multithreading applications are hard to debug.
  2. And makes the application more complex.

A thread is defined as the execution path of a program. Each thread defines a unique flow of control. If your application involves complicated and time consuming operations, then it is often helpful to set different execution paths or threads, with each thread performing a particular job. Threads are lightweight processes. One common example of use of thread is implementation of concurrent programming by modern operating systems. Use of threads saves wastage of CPU cycle and increase efficiency of an application. So far we wrote the programs where a single thread runs as a single process which is the running instance of the application. However, this way the application can perform one job at a time. To make it execute more than one task at a time, it could be divided into smaller threads.

Thread Life Cycle The life cycle of a thread starts when an object of the System.Threading.Thread class is created and ends when the thread is terminated or completes execution. Following are the various states in the life cycle of a thread: The Unstarted State: It is the situation when the instance of the thread is created but the Start method is not called. The Ready State: It is the situation when the thread is ready to run and waiting CPU cycle. The Not Runnable State: A thread is not executable, when: Sleep method has been called Wait method has been called Blocked by I/O operations The Dead State: It is the situation when the thread completes execution or is aborted.

Creating Threads-- Threads are created by extending the Thread class. The extended Thread class then calls the Start() method to begin the child thread execution.

Destroying Threads-- The Abort() method is used for destroying threads. The runtime aborts the thread by throwing a ThreadAbortException. This exception cannot be caught, the control is sent to the finally block, if any.

Difference between Convert.ToString() and ToString() Difference between System.String and System.Text.StringBuilder Indexers usage in .NET. CTS/CLS Object- .Net Architecture- Var vs Dynamic- Explain static attributes,static methods and static class? Garbage collection- Difference Between Application Exception and System Exception

Difference between Convert.ToString() and ToString() To understand the difference consider the example below. The ToString() method, expects the instance on which you are invoking to be NOT NULL. If the object is NULL, you get a Null Reference exception. using System; public class MainClass { public static void Main() { Customer C1 = null; Console.WriteLine(C1.ToString()); } } public class Customer { public string Name { get; set; } } On the other hand, Convert.ToString() returns an empty string if the object is NULL. using System; public class MainClass { public static void Main() { Customer C1 = null; Console.WriteLine(Convert.ToString(C1)); } } public class Customer { public string Name { get; set; } } So in summary, Convert.ToString() handles null, while ToString() doesn't, and throws a NULL reference exception. Depending on the type of the application, architecture and what you are trying to achieve, you choose one over the other. Difference between System.String and System.Text.StringBuilder

Strings of type StringBuilder are mutable whereas strings of type System.String are immutable. As StringBuilder objects are mutable, they offer better performance than string objects of type System.String, when heavy string manipulation is involved. using System; public class MainClass { public static void Main() { string userString = "C#"; userString += " Video"; userString += " Tutorial"; userString += " for"; userString += " beginners"; Console.WriteLine(userString); } } created object 5 times using System; using System.Text; namespace Pragim { public class MainClass { public static void Main() { StringBuilder userStringBuilder = new StringBuilder("C#"); userStringBuilder.Append(" Video"); userStringBuilder.Append(" Tutorial"); userStringBuilder.Append(" for"); userStringBuilder.Append(" beginners"); Console.WriteLine(userStringBuilder.ToString()); } } } only one object is created

  1. Objects of type StringBuilder are mutable where as objects of type System.String are immutable.
  2. As StringBuilder objects are mutable, they offer better performance than string objects of type System.String.
  3. StringBuilder class is present in System.Text namespace where String class is present in System namespace.

indexers usage in .NET. To retrieve data from a specific column when looping thru "SqlDataReader" object, we can use either the integral indexer or string indexer. string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString; using (SqlConnection con = new SqlConnection(CS)) { SqlCommand cmd = new SqlCommand("Select * from tblEmployee", con); con.Open(); SqlDataReader rdr = cmd.ExecuteReader(); while (rdr.Read()) { // Using integral indexer to retrieve Id column value Response.Write("Id = " + rdr[0].ToString() + " "); // Using string indexer to retrieve Id column value Response.Write("Name = " + rdr["Name"].ToString()); Response.Write("
"); } }

Right click on SqlDataReader class and select "Go To Definition", to view it's metadata. Notice that, there is an integral and string indexer defined.

CTS- it allows two different languages to communicate with each other.

CLS- It is a subset of cts It gives certain rules to the framework.

.Net Architecture-

Latest .NET Framework and Latest C# languages ? How many .Net based languages available ? Latest .net framework is 4.6

Explain static attributes,static methods and static class? The static modifier can be used with a class, field, method, property, operator, event or constructor. The static member is always accessed by the class name, not the instance name. Use the static modifier to declare a static member, which belongs to the type itself rather than to a specific object. using System; namespace staticexample { class Program { public static int i; public static void display() { i=10; Console.WriteLine(i); } public void demo() { int j=20; Console.WriteLine(j); }

    static void Main(string[] args)
    {
        Program obj = new Program();
        Program.display();
        obj.demo();
        Console.Read();
    }
}

} Here we have not used an instance of the class for the static method display(). However, for the nonstatic demo() method we need the instance of the class to call it. This is how to call static and non-static methods.

Static classs- 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. For example, if you have a static class that is named UtilityClass that has a public method named MethodA, you call the method as shown in the following example: UtilityClass.MethodA();

static System.Math class contains methods that perform mathematical operations, without any requirement to store or retrieve data that is unique to a particular instance of the Math class. double dub = -3.14;
Console.WriteLine(Math.Abs(dub));
Console.WriteLine(Math.Floor(dub));
Console.WriteLine(Math.Round(Math.Abs(dub)));

// Output:
// 3.14
// -4
// 3

Garbage collection- The Garbage collection is a very important technique in the .Net framework to free the unused managed code objects in the memory and free the space to the process.

Garbage Collection in .Net framework

The garbage collection (GC) is new feature in Microsoft .net framework. When we have a class that represents an object in the runtime that allocates a memory space in the heap memory. All the behavior of that objects can be done in the allotted memory in the heap. Once the activities related to that object is get finished then it will be there as unused space in the memory.

The earlier releases of Microsoft products have used a method like once the process of that object get finished then it will be cleared from the memory. For instance Visual Basic, An object get finishes that work then there we have to define a "nothing" to that object. So, it clears the memory space to the processors.

Microsoft was planning to introduce a method that should automate the cleaning of unused memory space in the heap after the life time of that object. Eventually they have introduced a new technique "Garbage collection". It is very important part in the .Net framework. Now it handles this object clear in the memory implicitly. It overcomes the existing explicit unused memory space clearance.

Garbage Collection

The heap memory is divided into number of generations. Normally it is three generations. The Generation 0 is for short live objects, Generation 1 is for medium live objects which are moved from Generation 0. Generation 3 is mostly stable objects.

When an object is created then it will allocate the memory space which will be higher. It will be in the Generation 0 and the memory allocation will be continuous without any space between the generations of garbage collectors.

How it works

Implicit Garbage Collection should be handled by the .Net framework. When object is created then it will be placed in the Generation 0. The garbage collection uses an algorithm which checks the objects in the generation, the objects life time get over then it will be removed from the memory. The two kinds of objects. One is Live Objects and Dead Objects. The Garbage collection algorithm collects all unused objects that are dead objects in the generation. If the live objects running for long time then based on that life time it will be moved to next generation.

The object cleaning in the generation will not take place exactly after the life time over of the particular objects. It takes own time to implement the sweeping algorithm to free the spaces to the process.

Exception Handling

The Garbage collection has designed such a way that it can be implicitly handling to collect the free spaces in memory. But as I said it takes own time to uses the algorithm to collect unused objects in the memory.

If we want to forces to collect unused objects or explicitly release particular object from the momory.The code allows us to clear the object from the heap immediately.

When it happens

The garbage collector periodically checks the heap memory to reclaim the objects when the object has no valid references in the memory.

When an object is created then it will allocate the memory in the heap then it checks the available space for the newly created objects, if the available space is not adequate to allot the space then it automatically garbage collect the unused objects. If all are valid referenced objects then it gets additional space from the processor.

If the object has reference with managed code objects then it will not free the memory space. However it cannot control the reference with unmanaged code objects, when application forces to collect the unused objects. But it can be achieved to write the explicit coding to avoid managed objects reference with unmanaged objects.

Example code to know more about Garbage Collection

The Microsoft framework System namespace have the GC class, which exposes more method and property about garbage collection.

MaxGeneration

This property in the GC class returns the total number of generations.
using System; class GCExample1 { public static void Main(string[] args) { try { Console.WriteLine("GC Maximum Generations:" + GC.MaxGeneration); } catch (Exception oEx) { Console.WriteLine("Error:" + oEx.Message); } } }

MaxGeneration property will return the highest generation in the garbage collection. It will be counted as total number of generations in the GC class which starts from 0.Here it has returned 2 as maxGeneration. That means totally three generations in the Garbage Collection. They are Generation 0, Generation 1 and Generation 2.

GetTotalMemory and GetGeneration

using System; class BaseGC { public void Display() { Console.WriteLine("Example Method"); } }

class GCExample2 { public static void Main(string[] args) { try { Console.WriteLine("Total Memory:" + GC.GetTotalMemory(false)); BaseGC oBaseGC = new BaseGC(); Console.WriteLine("BaseGC Generation is :" + GC.GetGeneration(oBaseGC)); Console.WriteLine("Total Memory:" + GC.GetTotalMemory(false)); } catch (Exception oEx) { Console.WriteLine("Error:" + oEx.Message); } }}

Here GetTotalMemory shows the total number of memory occupied by the various resources. Here I have added one more managed code objects in the heap memory. After adding, the size of the memory has increased.

The GetGeneration method will find out the particular managed object in the which generation. Here it shows the Object oBaseGC in the 0th generation.

CollectionCount and Collect using System; class Calci { public int Add(int a, int b) { return (a + b); } public int Sub(int a, int b) { return (a - b); } public int Multi(int a, int b) { return (a * b); } public int Divide(int a, int b) { return (a / b); } }

class GCExample3 { public static void Main(string[] args) { Calci oCalci = new Calci(); Console.WriteLine("Calci object is now on " + GC.GetGeneration(oCalci) + " Generation"); Console.WriteLine("Garbage Collection Occured in 0th Generation:" +GC.CollectionCount(0)); Console.WriteLine("Garbage Collection Occured in 1th Generation:" +GC.CollectionCount(1)); Console.WriteLine("Garbage Collection Occured in 2th Generation:" +GC.CollectionCount(2)); GC.Collect(0); Console.WriteLine("Garbage Collection Occured in 0th Generation:" +GC.CollectionCount(0)); } }

The CollectionCount helps us to find out the generation wise garbage collection occurred. As we know there are totally three generations in the garbage collector. Here I have passed argument as one for know the first generation. Initially it was 0. Then through the code I have collected the unused objects in the 0th generation. Again I have checked the CollectionCount in the 0thgeneration. Now it says 1.

The Collect method used to collect the unreferenced objects in the heap memory. It will clear the object and reclaim the memory space.

Difference Between Application Exception and System Exception

All exception derives from Exception Base class. system exception are all which are defined by .NET

A System level Exception is normally thrown when a nonrecoverable error has occurred, such as a database crash.

Application level Exceptions Application exceptions can be user defined exceptions thrown by the applications. If you are designing an application that needs to create its own exceptions class, you are advised to derive custom exceptions from the System.ApplicationException class. Eg: C# static void Main(string[] args) { //If there is no parameter found.. if (args.Length == 0) { throw new ArgumentException("No parameter found"); } }

3 ways to run c# program ONLINE Visual studio Csc compiler -> set C:\Windows\Microsoft.NET\Framework\v4.0.30319 on cmd prompt csc first.cs -> it generates a file first

internal : //The internal access modifiers can access within the program that contain its declarations and also access within the same assembly level but not from another assembly.

//private : //The scope of the accessibility is limited only inside the classes or struct in which they are declared. //The private members cannot be accessed outside the class and it is the least permissive access level.

//protected :- //The scope of accessibility is limited within the class or struct and the class derived (Inherited )from this class.

//protected internal : //Protected internal is the same access levels of both protected and internal. //It can access anywhere in the same assembly and in the same class also the classes inherited from the same class .

//public :- //public is the most common access specifier in C# . It can be access from anywhere, that means there is no restriction on accessibility. //The scope of the accessibility is inside class as well as outside. //The type or member can be accessed by any other code in the same assembly or another assembly that references it.

Enumerators can be used to read the data in the collection - foreach

stringBuilder is a dynamic object. It doesn’t create a new object in the memory but dynamically expands the needed memory to accommodate the modified or new string

A string is an object of type String whose value is text. Internally, the text is stored as a sequential read-only collection of Char objects. There is no null-terminating character at the end of a C# string; therefore a C# string can contain any number of embedded null characters ('\0'). The Length property of a string represents the number of Char objects it contains, not the number of Unicode characters. To access the individual Unicode code points in a string, use the StringInfo object.

In C#, the string keyword is an alias for String. Therefore, String and string are equivalent, and you can use whichever naming convention you prefer. The String class provides many methods for safely creating, manipulating, and comparing strings. In addition, the C# language overloads some operators to simplify common string operations.The maximum size of a String object in memory is 2GB, or about 1 billion characters.

String Escape Sequences Escape sequence Character name ' Single quote " Double quote \ Backslash \0 Null \a Alert \b Backspace \n New line \r Carriage return \t Horizontal tab

An index is the position of a Char object (not a Unicode character) in a String. An index is a zero-based, nonnegative number that starts from the first position in the string, which is index position zero. A number of search methods, such as IndexOf and LastIndexOf, return the index of a character or substring in the string instance.

The Chars property lets you access individual Char objects by their index position in the string. Because the Chars property is the default property (in Visual Basic) or the indexer (in C#), you can access the individual Char objects in a string by using code such as the following. This code looks for white space or punctuation characters in a string to determine how many words the string contains.

A string that has been declared but has not been assigned a value is null. Attempting to call methods on that string throws a NullReferenceException. A null string is different from an empty string, which is a string whose value is "" or String.Empty. In some cases, passing either a null string or an empty string as an argument in a method call throws an exception. For example, passing a null string to the Int32.Parse method throws an ArgumentNullException, and passing an empty string throws a FormatException.

A String object is called immutable (read-only), because its value cannot be modified after it has been created. Methods that appear to modify a String object actually return a new String object that contains the modification.

You can use the StringBuilder class instead of the String class for operations that make multiple changes to the value of a string. Unlike instances of the String class, StringBuilder objects are mutable; when you concatenate, append, or delete substrings from a string, the operations are performed on a single string. When you have finished modifying the value of a StringBuilder object, you can call its StringBuilder.ToString method to convert it to a string.

Array Overview

An array is a collection of similar data types.

Advantages: Arrays are strongly typed.

Disadvantages: Arrays cannot grow in size once initialized. Have to rely on integral indices to store or retrieve items from the array

An array has the following properties:

1. An array can be Single-Dimensional, Multidimensional or Jagged.

2. The number of dimensions and the length of each dimension are established when the array instance is created. These values can't be changed during the lifetime of the instance.

3. The new operator is used to create the array and initialize the array elements to their default values.The default values of numeric array elements are set to zero, and reference elements are set to null.

4. A jagged array is an array of arrays, and therefore its elements are reference types and are initialized to null.

5. Arrays are zero indexed: an array with n elements is indexed from 0 to n-1.

6. Array elements can be of any type, including an array type.

7. Array types are reference types derived from the abstract base type Array. Since this type implements IEnumerable and IEnumerable<T>, you can use foreach iteration on all arrays in C#.
  1. In C#, arrays are actually objects, and not just addressable regions of contiguous memory as in C and C++. Array is the abstract base type of all array types. You can use the properties, and other class members, that Array has.

  2. You can store multiple variables of the same type in an array data structure. You declare an array by specifying the type of its elements.

  3. Various ways to work with arrays ( single, multi-demensional , jagged ):

11.A jagged array is an array whose elements are arrays. The elements of a jagged array can be of different dimensions and sizes. A jagged array is sometimes called an "array of arrays."

  1. The following is a declaration of a single-dimensional array that has three elements, each of which is a single-dimensional array of integers: int[][] jaggedArray = new int[3][];

  2. A jagged array is an array of arrays, and therefore its elements are reference types and are initialized to null.

  3. It is possible to mix jagged and multidimensional arrays. The following is a declaration and initialization of a single-dimensional jagged array that contains three two-dimensional array elements of different sizes. Ex: int[][,] jaggedArray4 = new int[3][,] { new int[,] { {1,3}, {5,7} }, new int[,] { {0,2}, {4,6}, {8,10} }, new int[,] { {11,22}, {99,88}, {0,9} } };

  4. The method Length returns the number of arrays contained in the jagged array.

  5. You can use foreach loop to iterate the elements for both single and multi-dimensional array. 15.Arrays can be passed as arguments to method parameters. Because arrays are reference types, the method can change the value of the elements.

  6. You can also use ref and out keyword to pass array as parameter . Note : Please find the difference between passing array as paremeter without ref and with ref. 17.You can create an implicitly-typed array in which the type of the array instance is inferred from the elements specified in the array initializer. Implicitly-typed arrays are usually used in query expressions together with anonymous types and object and collection initializers.

About Array Class

  1. Array class Provides methods for creating, manipulating, searching, and sorting arrays, thereby serving as the base class for all arrays in the common language runtime.

  2. The Array class is not part of the System.Collections namespaces. However, it is still considered a collection because it is based on the IList interface.

  3. The Array class is the base class for language implementations that support arrays. However, only the system and compilers can derive explicitly from the Array class. Users should employ the array constructs provided by the language.

23.An element is a value in an Array. The length of an Array is the total number of elements it can contain. The lower bound of an Array is the index of its first element. An Array can have any lower bound, but it has a lower bound of zero by default.

24.A multidimensional Array can have different bounds for each dimension.

  1. An array can have a maximum of 32 dimensions.

26.Unlike the classes in the System.Collections namespaces, Array has a fixed capacity. To increase the capacity, you must create a new Array object with the required capacity, copy the elements from the old Array object to the new one, and delete the old Array.

27.By default, the maximum size of an Array is 2 gigabytes (GB).

  1. Starting with the .NET Framework 2.0, the Array class implements the System.Collections.Generic.IList, System.Collections.Generic.ICollection, and System.Collections.Generic.IEnumerable generic interfaces. The implementations are provided to arrays at run time, and as a result, the generic interfaces do not appear in the declaration syntax for the Array class.

29.The Array.Copy method copies elements not only between arrays of the same type but also between standard arrays of different types; it handles type casting automatically.

  1. Learn the working of Some methods of Array class, such as CreateInstance, Copy, CopyTo, GetValue, and SetValue. 31.Explore all used methods and properties for array. Properties Overwiew

1.A property is a member that provides a flexible mechanism to read, write, or compute the value of a private field. Properties can be used as if they are public data members, but they are actually special methods called accessors. 2.This enables data to be accessed easily and still helps promote the safety and flexibility of methods. 3.Properties enable a class to expose a public way of getting and setting values, while hiding implementation or verification code 4.A get property accessor is used to return the property value, and a set accessor is used to assign a new value. These accessors can have different access levels. 5.The value keyword is used to define the value being assigned by the set accessor. 6.Properties that do not implement a set accessor are read only. 7. Properties are like smart fields. 8. Properties can also be static. If a property is static, there are limitations on what the get and set methods can do. 9.The type of a property can be a primitive type, a collection of primitive types, a user-defined type, or a collection of user-defined types. 10.When the data type of a property is an enumeration, a development environment such as Microsoft Visual Studio will display the property as a drop-down list in the Properties window. 11. If the data type of a property is a class that has properties, those properties are called subproperties of the defining property. 12.You should expose properties instead of public fields from your components, because properties can be versioned, they allow data hiding, and the accessor methods can execute additional logic. 13.It is common to have properties that simply return immediately with the result of an expression. There is a syntax shortcut for defining these properties using =>: public string Name => First + " " + Last; The property must be read only, and you do not use the get accessor keyword. 14.Properties combine aspects of both fields and methods. 15. A property without a set accessor is considered read-only. A property without a get accessor is considered write-only. A property that has both accessors is read-write 16.Unlike fields, properties are not classified as variables. Therefore, you cannot pass a property as a ref or out parameter. 17.Properties have many uses: they can validate data before allowing a change; they can transparently expose data on a class where that data is actually retrieved from some other source, such as a database; they can take an action when data is changed, such as raising an event, or changing the value of other fields. 18.Properties can be marked as public, private, protected, internal, or protected internal 19.A property may be marked as a virtual property by using the virtual keyword. This enables derived classes to override the property behavior by using the override keyword. 20.A property overriding a virtual property can also be sealed, specifying that for derived classes it is no longer virtual. 21.a property can be declared abstract, This means that there is no implementation in the class, and derived classes must write their own implementation. 22.It is an error to use a virtual, abstract, or override modifier on an accessor of a static property. 23.Properties can be declared on an interface. 24.The get and set portions of a property or indexer are called accessors. By default these accessors have the same visibility, or access level: that of the property or indexer to which they belong.

25.it is sometimes useful to restrict access to one of these accessors. Typically, this involves restricting the accessibility of the set accessor, while keeping the get accessor publicly accessible. For example:

Restrictions on Access Modifiers on Accessors

Using the accessor modifiers on properties or indexers is subject to these conditions: You cannot use accessor modifiers on an interface or an explicit interface member implementation. You can use accessor modifiers only if the property or indexer has both set and get accessors. In this case, the modifier is permitted on one only of the two accessors. If the property or indexer has an override modifier, the accessor modifier must match the accessor of the overridden accessor, if any. The accessibility level on the accessor must be more restrictive than the accessibility level on the property or indexer itself.

Implicitly Typed Local Variables

Local variables can be given an inferred "type" of var instead of an explicit type. The var keyword instructs the compiler to infer the type of the variable from the expression on the right side of the initialization statement. The inferred type may be a built-in type, an anonymous type, a user-defined type, or a type defined in the .NET Framework class library.

It is important to understand that the var keyword does not mean "variant" and does not indicate that the variable is loosely typed, or late-bound. It just means that the compiler determines and assigns the most appropriate type.

The var keyword may be used in the following contexts:

  1. On local variables (variables declared at method scope) as shown in the previous example.
  2. In a for initialization statement: for(var x = 1; x < 10; x++) {}
  3. In a foreach initialization statement: foreach(var item in list){...}
    4.In a using statement : using (var file = new StreamReader("C:\myfile.txt")) {...}

The following restrictions apply to implicitly-typed variable declarations:

1.var can only be used when a local variable is declared and initialized in the same statement; the variable cannot be initialized to null, or to a method group or an anonymous function.

  1. var cannot be used on fields at class scope.

  2. Variables declared by using var cannot be used in the initialization expression. In other words, this expression is legal: int i = (i = 20); but this expression produces a compile-time error: var i = (i = 20);

  3. Multiple implicitly-typed variables cannot be initialized in the same statement.

  4. If a type named var is in scope, then the var keyword will resolve to that type name and will not be treated as part of an implicitly typed local variable declaration.

Note : However, the use of var does have at least the potential to make your code more difficult to understand for other developers. For that reason, the C# documentation generally uses var only when it is required.
Fields----------------------------------------------------------------

1.A field is a variable of any type that is declared directly in a class or struct. Fields are members of their containing type.

2.A class or struct may have instance fields or static fields or both. Instance fields are specific to an instance of a type. If you have a class T, with an instance field F, you can create two objects of type T, and modify the value of F in each object without affecting the value in the other object. By contrast, a static field belongs to the class itself, and is shared among all instances of that class. Changes made from instance A will be visibly immediately to instances B and C if they access the field.

3.Generally, you should use fields only for variables that have private or protected accessibility.

4.Data that your class exposes to client code should be provided through methods, properties and indexers.

5.A private field that stores the data exposed by a public property is called a backing store or backing field.

6.Fields typically store the data that must be accessible to more than one class method and must be stored for longer than the lifetime of any single method.

7.Variables that are not used outside the scope of a single method should be declared as local variables within the method body itself.

8.Fields are initialized immediately before the constructor for the object instance is called. If the constructor assigns the value of a field, it will overwrite any value given during field declaration.

9.Fields can be marked as public, private, protected, internal, or protected internal. These access modifiers define how users of the class can access the fields

10.A field can optionally be declared static. This makes the field available to callers at any time, even if no instance of the class exists

11.A field can be declared readonly. A read-only field can only be assigned a value during initialization or in a constructor. A static readonly field is very similar to a constant, except that the C# compiler does not have access to the value of a static read-only field at compile time, only at run time.

13.To access a field in an object, add a period after the object name, followed by the name of the field, as in objectname.fieldname. For example:

CalendarEntry birthday = new CalendarEntry(); birthday.day = "Saturday";

14.A field can be given an initial value by using the assignment operator when the field is declared. To automatically assign the day field to "Monday", for example, you would declare day as in the following example:

C#

public class CalendarDateWithInitialization
{
    public string day = "Monday";
    //...
}

15.Fields are initialized immediately before the constructor for the object instance is called. If the constructor assigns the value of a field, it will overwrite any value given during field declaration.

Classes---------------------------------------------------------

  1. A class is like a blueprint. It defines the data and behavior of a type.
  2. A class is a construct that enables you to create your own custom types by grouping together variables of other types, methods and events.
  3. If the class is not declared as static, client code can use it by creating objects or instances which are assigned to a variable. The variable remains in memory until all references to it go out of scope.At that time, the CLR marks it as eligible for garbage collection.
  4. If the class is declared as static, then only one copy exists in memory and client code can only access it through the class itself, not an instance variable.
  5. Although they are sometimes used interchangeably, a class and an object are different things. A class defines a type of object, but it is not an object itself. An object is a concrete entity based on a class, and is sometimes referred to as an instance of a class. Objects can be created by using the new keyword followed by the name of the class that the object will be based on. 6.Only single inheritance is allowed in C#. In other words, a class can inherit implementation from one base class only. However, a class can implement more than one interface. 7.Classes that you declare directly within a namespace, not nested within other classes, can be either public or internal. Classes are internal by default.

-------------------------------------------------------------Objects -------------------------

1.An object is basically a block of memory that has been allocated and configured according to the blueprint of class. 2.A program may create many objects of the same class. 3.Objects are also called instances, and they can be stored in either a named variable or in an array or collection. 4.In an object-oriented language such as C#, a typical program consists of multiple objects interacting dynamically. 5.Because classes are reference types, a variable of a class object holds a reference to the address of the object on the managed heap. If a second object of the same type is assigned to the first object, then both variables refer to the object at that address. 6.Instances of classes are created by using the new operator. 7.Because structs are value types, a variable of a struct object holds a copy of the entire object. Instances of structs can also be created by using the new operator, but this is not required 8.It is not possible to deterministically destroy a class object like you can in C++. 9.When you compare two objects for equality, you must first distinguish whether you want to know whether the two variables represent the same object in memory, or whether the values of one or more of their fields are equivalent. If you are intending to compare values, you must consider whether the objects are instances of value types (structs) or reference types (classes, delegates, arrays). 10.To determine whether two class instances refer to the same location in memory (which means that they have the same identity), use the static Equals method. (System.Object is the implicit base class for all value types and reference types, including user-defined structs and classes.) 11.To determine whether the instance fields in two struct instances have the same values, use the ValueType.Equals method. Because all structs implicitly inherit from System.ValueType, you call the method directly on your object

Note :

  1. The System.ValueType implementation of Equals uses reflection because it must be able to determine what the fields are in any struct. When creating your own structs, override the Equals method to provide an efficient equality algorithm that is specific to your type.

2.To determine whether the values of the fields in two class instances are equal, you might be able to use the Equals method or the == operator. However, only use them if the class has overridden or overloaded them to provide a custom definition of what "equality" means for objects of that type. The class might also implement the IEquatable interface or the IEqualityComparer interface. Both interfaces provide methods that can be used to test value equality.

3.The allocation and deallocation of memory on the managed heap is highly optimized in the common language runtime. In most cases there is no significant difference in the performance cost of allocating a class instance on the heap versus allocating a struct instance on the stack.

Classes and structs have members that represent their data and behavior. A class's members include all the members declared in the class, along with all members (except constructors and destructors) declared in all classes in its inheritance hierarchy. Private members in base classes are inherited but are not accessible from derived classes.

The following table lists the kinds of members a class or struct may contain:


Fields

Fields are variables declared at class scope. A field may be a built-in numeric type or an instance of another class. For example, a calendar class may have a field that contains the current date.


Constants

Constants are fields or properties whose value is set at compile time and cannot be changed.


Properties

Properties are methods on a class that are accessed as if they were fields on that class. A property can provide protection for a class field to keep it from being changed without the knowledge of the object.


Methods

Methods define the actions that a class can perform. Methods can take parameters that provide input data, and can return output data through parameters. Methods can also return a value directly, without using a parameter.


Events

Events provide notifications about occurrences, such as button clicks or the successful completion of a method, to other objects. Events are defined and triggered by using delegates.


Operators

Overloaded operators are considered class members. When you overload an operator, you define it as a public static method in a class. The predefined operators (+, *, <, and so on) are not considered members. For more information, see Overloadable Operators.


Indexers

Indexers enable an object to be indexed in a manner similar to arrays.


Constructors

Constructors are methods that are called when the object is first created. They are often used to initialize the data of an object.


Destructors

Destructors are used very rarely in C#. They are methods that are called by the runtime execution engine when the object is about to be removed from memory. They are generally used to make sure that any resources which must be released are handled appropriately.


Nested Types

Nested types are types declared within another type. Nested types are often used to describe objects that are used only by the types that contain them.

Note : Access the individual files to read more about each class member.

A DLL is a library that contains code and data that can be used by more than one program at the same time. In C#, a DLL is a compiled assembly that contains .NET Framework code. It is created by compiling one or more C# source files into a DLL file.

Shortcuts- When viewing a document: Edit / Advanced / Word Wrap (Ctrl+E+W) CTRL+KC (comment) CTRL+KU (un-comment)

Press Ctrl+, - search

Then you will see a docked window under name of "Go to all"

This a picture of the "Go to all" in my IDE

dotnet --version

.\ - sql server pat

If we want to format the whole codewe need to press [CTRL + K + D]. In case we need to format only a part of the code, we need to mark this part with the mouse and press [CTRL + K + F]

http://csharpindepth.com/Articles/General/Strings.aspx https://msdn.microsoft.com/en-us/library/ms228362.aspx https://msdn.microsoft.com/en-us/library/hh127989(VS.88).aspx https://msdn.microsoft.com/en-us/library/362314fe.aspx https://msdn.microsoft.com/en-us/library/system.string(v=vs.110).aspx http://www.completecsharptutorial.com/csharp-articles/csharp-string-function/ http://www.dotnetcurry.com/csharp/189/csharp-string-substring-split-functions https://www.tutorialspoint.com/csharp/csharp_strings.htm

https://msdn.microsoft.com/en-us/library/system.random(v=vs.110).aspx http://csharpindepth.com/Articles/Chapter12/Random.aspx

https://msdn.microsoft.com/en-us/library/9b9dty7d.aspx https://msdn.microsoft.com/en-us/library/system.array(v=vs.110).aspx https://msdn.microsoft.com/en-us/library/aa288453(v=vs.71).aspx

Attributes Attributes allow you to add declarative information to your programs. This information can then be queried at runtime using reflection. There are several Pre-defined Attributes provided by .NET. It is also possible to create your own Custom Attributes. Creating custom attributes is beyond the scope of this article. A few pre-defined attributes with in the .NET framework. Obsolete - Marks types and type members outdated WebMethod - To expose a method as an XML Web service method Serializable - Indicates that a class can be serialized Example program using pre defined Obsolete attribute: Obsolete attribute can be used with types or type members that are obsolete (Outdated). If a developer uses a type or a type member that is decorated with obsolete attribute, the compiler issues a warning or an error depending on how the attribute is configured. In this sample program, Add(int FirstNumber, int SecondNumber) method is decorated with [Obsolete] attribute. If you compile this program, in the output window you will see a warning message (Compile complete -- 0 errors, 1 warnings). Also, visual studio, shows a green squiggly line under the Add(int FirstNumber, int SecondNumber) method. If you hover the mouse over the squiggly line, you should see the warning message. Note: If you don't see the warning message (Compile complete -- 0 errors, 1 warnings), rebuild the soultion. using System; using System.Collections.Generic; public class MainClass { private static void Main() { Calculator.Add(10, 15); } } public class Calculator { [Obsolete] public static int Add(int FirstNumber, int SecondNumber) { return FirstNumber + SecondNumber; } public static int Add(List Numbers) { int Sum = 0; foreach (int Number in Numbers) { Sum = Sum + Number; } return Sum; } }

The warning message says 'Calculator.Add(int, int)' is obsolete. However, this message is not completely useful, because it says 'Calculator.Add(int, int)' is obsolete, but not tell us which other method should we be using instead. So this is when we can customize, the warning message using attribute parameters.

The intention of the developer of Calculator class is that, he wanted us to use Add(List Numbers), instead of int Add(int FirstNumber, int SecondNumber). To communicate this message we can customize the warning message using attribute parameters as shown below. With this customization we are not only communicating that Add(int FirstNumber, int SecondNumber) method is obsolete, we are also telling to use the alternative method that is available. [Obsolete("Use Add(List Numbers) instead")] public static int Add(int FirstNumber, int SecondNumber)

If you want to generate a compiler error instead of warning, pass true for the bool error parameter of the Obsolete attribute as shown below. Now, we can't even compile the program.

[Obsolete("Use Add(List Numbers) instead", true)] public static int Add(int FirstNumber, int SecondNumber)

Finally, If you right click on Obsolete attribute and select Go To Definition, you will see that, an attribute is nothing but a class that inherits from System.Attribute base class.

Using Attributes With C# .NET

Attributes are like adjectives, which are used for metadata annotation that can be applied to a given type, assembly, module, method and so on. The .NET framework stipulates two types of attribute implementations, which are Predefined Attributes and Custom Attributes.

Attributes are types derived from the System.Attribute class. This is an abstract class defining the required services of any attribute. The following is the syntax of an attribute;

[type: attributeName(parameter1, parameter2,.........n)]

The attribute name is the class name of the attribute. Attributes can have zero or more parameters. The following code sample states the attributes implementation in which we are declaring a method as deprecated using the obsolete attribute:

using System; namespace attributes { class Program { static void Main(string[] args) { Console.WriteLine("Attributes sample"); TestMethod(); Console.ReadKey();
} [Obsolete("Deprecated Method",false)] public static void TestMethod() { Console.WriteLine("Hello world");
} } }

The following figure shows the MSIL code of the TestMethod method as displayed in ILDASM. Notice the custom directive that defines the Obsolete attribute.

Role of Attributes

Attributes might be useful for documentation purposes.

Predefined Attributes

The predefined attributes have been defined by Microsoft as a part of .NET FCL, and many of them receive special support from the C# compiler. Which implies that for those specific attributes, the compiler could customize the compilation process in a specific way.

The System.Attribute base class library provides a number of attributes in various namespaces. The following table gives a snapshot of some predefined attributes.

Attributes [Serialization] [NonSerialization] [Obsolete] [DllImport] [WebMethod] [CLSCompliant]

Description By marking this attributes, a class is able to persist its current state into stream. It specify that a given class or filed should not persisted during the serialization process. It is used to mark a member or type as deprecated. If they are attempted to be used somewhere else then compiler issues a warning message. This allows .NET code to make call an unmanaged C or C++ library. This is used to build XML web services and the marked method is being invoked by HTTP request. Enforce the annotated items to conform to the semantics of CLS.

To illustrate the predefined attributes in action, let's create a console based application to apply the implementation of them.

[Serialization] and [NonSerialization]

Here, assume that you have developed a Test class that can be persisted in a binary format using the [Serialization] attribute.

[Serializable] public class test { public Test() { } string name; string coutnry; [NonSerialized] int salary; }

Once the class has been compiled, you can view the extra metadata using the ildasm.exe utility. Notice the red triangle, where these attributes are recorded using the serializable token and the salary field is tokenized using the nonserilaized attribute as in the following.

[WebMethod]

The following example depicts the implementation of XML web services. Here, the UtilityWebService class is annotated with [WebService] attributes. This class defines two methods marked with [WebMethod] attributes.

[WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. // [System.Web.Script.Services.ScriptService] public class UtilityWebService : System.Web.Services.WebService { public UtilityWebService () { //Uncomment the following line if using designed components //InitializeComponent(); } [WebMethod] public string HelloWorld() { return "Hello World"; } [WebMethod] public int addition(int a,int b) { return a+b; }
}

To refer to the usage of [WebMethod] you may refer to my artile on C# Corner http://www.c-sharpcorner.com/UploadFile/84c85b/net-web-services/

[DLLImport]

The following code plays around with the unmanaged assembly user32.dll to utilize its existing method using the [DLLImport] attributes.

using System; using System.Runtime.InteropServices; namespace attributes { public class Test { [DllImport("user32.dll", EntryPoint = "MessageBox")] public static extern int ShowMessageBox(int hWnd,string text, string caption,uint type); } class Program { static void Main(string[] args) { string caption = "Hello World"; string text = "Sample Article on DLLImport Attribute"; test.ShowMessageBox(0, text, caption, 0);
Console.ReadKey();
}
} }

Note: a member can assign more than one attribute and can be applied multiple times itself.

Once this code is compiled successfully, it produces the following output as in the following:

[CLSCompliant]

If you annotate this attribute at the assembly or module level and you try to use the following non CLR compliant code, then the compiler issues a warning message.

To refer to the usage of [CLSCompliant] you may refer to my artile on C# Corner http://www.c-sharpcorner.com/UploadFile/84c85b/cross-language-interoperability-with-C-Sharp-net/

Custom Attributes

We can create custom attributes for private usage or to be published in a library for others. The following steps are the definitive procedure for creating custom attributes: The custom attribute class should be derived from System.Attribute The Attribute name should suffixed by "Attribute". Set the probable targets with the AttributeUsage attribute. Implement the class constructor and write-accessible properties. The first step in building a custom attribute is to create a new class FunWith with Attribute suffix that derives from the System.Attribute class. Then define the class constructor and write an accessible property as Company subsequently.

[AttributeUsage(AttributeTargets.Class)] public class FunwithAttribute : Attribute { public FunwithAttribute(string s) { this.Company = s; } public string Company { get; set; } }

It is now time to apply a custom attribute class on another class. So we are creating another class test which has a FunWith attribute annotation in which we are passing the company name information.

[Funwith("HCL Technology")] public class test { public test(string name, string country) { this.EmpName = name; this.Country = country;
} public string FullDetails() { string str = EmpName + "-" + Country; return str; } private string EmpName; private string Country; } class Program { static void Main(string[] args) { test obj = new test("Vidya Vrat","India"); Console.WriteLine("Result:{0}",obj.FullDetails()); Console.ReadKey();
} }

After compiling this program, it yields the following output.

Output

Result: Vidya Vrat - India

Well, as you can notice, the custom attribute does not impose any impact on the final output. But we can reveal the annotation that occurs by attributes at the metadata level using ildasm.exe as in the following;

Custom defined attributes are sometimes valuable simply as information. However, the real power lies in associating with an attribute. You can read custom attributes with reflection using Attribute.GetCustomAttribute and Type.

The following code accesses the custom attribute values at runtime using reflection. Here, we are storing the custom attribute members in an array of object types, then looping through it to get the property value.

static void Main(string[] args) { MemberInfo info = typeof(test); object[] attrib = info.GetCustomAttributes(typeof(FunwithAttribute), false); foreach (Object attribute in attrib) { FunwithAttribute a = (FunwithAttribute)attribute; Console.WriteLine("Company: {0}", a.Company);
} }

The following code illustrates the actual utilization of custom attribute values. Here, I am displaying some values based on the custom attribute's Boolean value. The output varies on status True or False values.

using System; using System.Reflection;
public class CheckStatus : Attribute { private bool Val = false; public bool status { get { return Val; } } public CheckStatus(bool val) { Val = val; } }

Now we are annotating the Custom Attribute in the Test class. Here, we need to configure the CheckStatus value to true to false manually. In the FullDetails() method, we are accessing the custom attributes members by foreach loop construct and later we are checking whether the status value is true or false.

[CheckStatus(false)] public class test { private string EmpName; private string Country; public test(string name, string country) { this.EmpName = name; this.Country = country;
} public string FullDetails() { string str = null; Type type = this.GetType(); CheckStatus[] attrib = (CheckStatus[])type.GetCustomAttributes(typeof(CheckStatus), false); if (attrib[0].status == true) { str = EmpName + "-" + Country; } else { str = "Hi " + EmpName; } return str; } } class Program { static void Main(string[] args) { test obj = new test("Vidya Vrat","India"); Console.WriteLine("Result:{0}",obj.FullDetails()); Console.ReadKey();
} }

After successfully compiling this code, the following figure depicts the output from both cases:

Result : Vidya Vrat - India Status = True Result: Hi Vidya Vrat Starus = False

Rather than applying attributes on an individual type, it is also possible to apply an attribute on all the types within a given assembly. To do so, simply add the attributes at assembly level in the AssemblyInfo.cs file. This file is a handy place to put attributes to be applied at the assembly level.

using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices;

[assembly: AssemblyTitle("CustomAttribute")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("CustomAttribute")] [assembly: AssemblyCopyright("Copyright © 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: Guid("ce5fc30b-e670-4115-aa64-4be10e7b6ea9")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]

using System declaration - The namespace declaration, using System, indicates that you are using the System namespace. If you omit the using System, declaration, then you have to use the fully qualified name of the Console class. A namespace is used to organize your code and is collection of classes, interfaces, structs, enums and delegates like system-namespace console-class

The out-keyword describes parameters whose actual variable locations are copied onto the stack of the called method.Out parameters are similar to reference parameters

Reflection objects are used for obtaining type information at runtime. The classes that give access to the metadata of a running program are in the System.Reflection namespace. The System.Reflection namespace contains classes that allow you to obtain information about the application and to dynamically add types, values, and objects to the application.

Reflection has the following applications: It allows view attribute information at runtime. It allows examining various types in an assembly and instantiate these types. It allows late binding to methods and properties It allows creating new types at runtime and then performs some tasks using those types.

Sealed classes Sealed classes are used to restrict the inheritance feature of object oriented programming. Once a class is defined as a sealed class, the class cannot be inherited. A sealed class cannot also be an abstract class. Because abstract class has to provide functionality and here we are restricting it to inherit. static A static field is not part of a specific instance; instead, it identifies exactly one storage location. No matter how many instances of a class are created, there is only ever one copy of a static field for the associated application domain. struct 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. AddRange() - Add() method allows you to add one item at a time to the end of the list, where as AddRange() allows you to add another list of items, to the end of the list.

  1. GetRange() - Using an item index, we can retrieve only one item at a time from the list, if you want to get a list of items from the list, then use GetRange() function. This function expects 2 parameters, i.e the start index in the list and the number of elements to return.

  2. InsertRange() - Insert() method allows you to insert a single item into the list at a specificed index, where as InsertRange() allows you, to insert another list of items to your list at the specified index.

  3. RemoveRange() - Remove() function removes only the first matching item from the list. RemoveAt() function, removes the item at the specified index in the list. RemoveAll() function removes all the items that matches the specified condition. RemoveRange() method removes a range of elements from the list. This function expects 2 parameters, i.e the start index in the list and the number of elements to remove. If you want to remove all the elements from the list without specifying any condition, then use Clear() function.

A C# string is an array of characters declared using the string keyword. String objects are immutable, meaning that they cannot be changed once they have been created.

What is C# null ? The null keyword is a special case for a variable value. The implementation of C# on the CLR represents a null reference by zero bits. When defining a string in a class, dont initialize it to null. Instead, initialize it to the constant string.Empty. A null string does not refer to an instance of a System.String object and any attempt to call a method on a null string results in a NullReferenceException.

What is Empty Strings ? An empty string is an instance of a System.String object that contains zero characters. You can call methods on empty strings because they are valid System.String objects.

IsNullOrEmpty method IsNullOrEmpty is a convenience method that enables you to simultaneously test whether a String is null or its value is Empty.

NullReferenceException NullReferenceException indicates that you are trying to access member fields, or function types, on an object reference that points to null. That means the reference to an Object which is not initialized.