Question 1

  • November 2019
  • PDF

This document was uploaded by user and they confirmed that they have the permission to share it. If you are author or own the copyright of this book, please report to us by using this DMCA report form. Report DMCA


Overview

Download & View Question 1 as PDF for free.

More details

  • Words: 22,035
  • Pages: 68
Dot net download Use the static modifier to declare a static member, which belongs to the type itself rather than to a specific object. The static modifier can be used with classes, fields, methods, properties, operators, events and constructors, but cannot be used with indexers, destructors, or types other than classes. For example, the following class is declared as static, and contains only static methods: C#, the new keyword can be used as an operator, a modifier, or a constraint. new Operator Used to create objects and invoke constructors. new Modifier Used to hide an inherited member from a base class member. new Constraint Used to restrict types that might be used as arguments for a type parameter in a generic declaration.

Static classes and class members are used to create data and functions that can be accessed without creating an instance of the class. Static class members can be used to separate data and behavior that is independent of any object identity: the data and functions do not change regardless of what happens to the object. Static classes can be used when there is no data or behavior in the class that depends on object identity. Static Classes A class can be declared static, indicating that it contains only static members. It is not possible to create instances of a static class using the new keyword. Static classes are loaded automatically by the .NET Framework common language runtime (CLR) when the program or namespace containing the class is loaded. Use a static class to contain methods that are not associated with a particular object. For example, it is a common requirement to create a set of methods that do not act on instance data and are not associated to a specific object in your code. You could use a static class to hold those methods. The main features of a static class are:

• • • •

They only contain static members. They cannot be instantiated. They are sealed. They cannot contain Instance Constructors (C# Programming Guide). Creating a static class is therefore much the same as creating a class that contains only static members and a private constructor. A private constructor prevents the class from being instantiated. The advantage of using a static class is that the compiler can check to make sure that no instance members are accidentally added. The compiler will guarantee that instances of this class cannot be created. Static classes are sealed and therefore cannot be inherited. Static classes cannot contain a constructor, although it is still possible to declare a static constructor to assign initial values or set up some static state. For more information, see Static Constructors (C# Programming Guide). When to Use Static Classes Suppose you have a class CompanyInfo that contains the following methods to get information about the company name and address. C#

Copy Code

class CompanyInfo { public string GetCompanyName() { return "CompanyName"; } public string GetCompanyAddress() { return "CompanyAddress"; } //... } These methods do not need to be attached to a specific instance of the class. Therefore, instead of creating unnecessary instances of this class, you can declare it as a static class, like this: C#

Copy Code

static class CompanyInfo { public static string GetCompanyName() { return "CompanyName"; } public static string GetCompanyAddress() { return "CompanyAddress"; }

//... } Use a static class as a unit of organization for methods not associated with particular objects. Also, a static class can make your implementation simpler and faster because you do not have to create an object in order to call its methods. It is useful to organize the methods inside the class in a meaningful way, such as the methods of the Math class in the System namespace. Static Members A static method, field, property, or event is callable on a class even when no instance of the class has been created. If any instances of the class are created, they cannot be used to access the static member. Only one copy of static fields and events exists, and static methods and properties can only access static fields and static events. Static members are often used to represent data or calculations that do not change in response to object state; for instance, a math library might contain static methods for calculating sine and cosine. Static class members are declared using the static keyword before the return type of the member, for example: C#

Copy Code

public class Automobile { public static int NumberOfWheels = 4; public static int SizeOfGasTank { get { return 15; } } public static void Drive() { } public static event EventType RunOutOfGas; //other non-static fields and properties... } Static members are initialized before the static member is accessed for the first time, and before the static constructor, if any is called. To access a static class member, use the name of the class instead of a variable name to specify the location of the member. For example: C#

Copy Code

Automobile.Drive(); int i = Automobile.NumberOfWheels; Example Here is an example of a static class that contains two methods that convert temperature from Celsius to Fahrenheit and vice versa: C#

Copy Code

public static class TemperatureConverter { public static double CelsiusToFahrenheit(string temperatureCelsius) { // Convert argument to double for calculations. double celsius = System.Double.Parse(temperatureCelsius); // Convert Celsius to Fahrenheit. double fahrenheit = (celsius * 9 / 5) + 32; return fahrenheit; } public static double FahrenheitToCelsius(string temperatureFahrenheit) { // Convert argument to double for calculations. double fahrenheit = System.Double.Parse(temperatureFahrenheit); // Convert Fahrenheit to Celsius. double celsius = (fahrenheit - 32) * 5 / 9;

return celsius; } } class TestTemperatureConverter { static void Main() { System.Console.WriteLine("Please select the convertor direction"); System.Console.WriteLine("1. From Celsius to Fahrenheit."); System.Console.WriteLine("2. From Fahrenheit to Celsius."); System.Console.Write(":"); string selection = System.Console.ReadLine(); double F, C = 0; switch (selection) { case "1": System.Console.Write("Please enter the Celsius temperature: "); F = TemperatureConverter.CelsiusToFahrenheit(System.Console.ReadLine()); System.Console.WriteLine("Temperature in Fahrenheit: {0:F2}", F); break; case "2": System.Console.Write("Please enter the Fahrenheit temperature: "); C = TemperatureConverter.FahrenheitToCelsius(System.Console.ReadLine()); System.Console.WriteLine("Temperature in Celsius: {0:F2}", C); break; default: System.Console.WriteLine("Please select a convertor."); break; } } } Input 2 98.6 Sample Output: Please select the convertor 1. From Celsius to Fahrenheit. 2. From Fahrenheit to Celsius. :2 Please enter the Fahrenheit temperature: 98.6 Temperature in Celsius: 37.00 Additional sample output might look as follows: Please select the convertor 1. From Celsius to Fahrenheit. 2. From Fahrenheit to Celsius. :1 Please enter the Celsius temperature: 37.00 Temperature in Fahrenheit: 98.60

A static constructor is used to initialize any static data, or to perform a particular action that needs performed once only. It is called automatically before the first instance is created or any static members are referenced. C#

Copy Code

class SimpleClass { // Static constructor static SimpleClass() { //... } } Static constructors have the following properties:

• • • • • •

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. 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 constructors are also useful when creating wrapper classes for unmanaged code, when the constructor can call the LoadLibrary method. Example In this example, the class Bus has a static constructor and one static member, Drive(). When Drive() is called, the static constructor is invoked to initialize the class. C#

Copy Code

public class Bus { // Static constructor: static Bus() { System.Console.WriteLine("The static constructor invoked."); } public static void Drive() { System.Console.WriteLine("The Drive method invoked."); } } class TestBus { static void Main() { Bus.Drive(); } }

C#

Copy Code

class CoOrds { public int x, y; // constructor public CoOrds() { x = 0; y = 0; } } Note For clarity, this class contains public data members. This is not a recommended programming practice because it allows any method anywhere in a program unrestricted and unverified access to an object's inner workings. Data members should generally be private, and should be accessed only through class methods and properties.

Output The static constructor invoked. The Drive method invoked.

Instance constructors are used to create and initialize instances. The class constructor is invoked when you create a new object, for example: This constructor is called whenever an object based on the CoOrds class is created. A constructor like this one, which takes no arguments, is called a default constructor. However, it is often useful to provide additional constructors. For example, we can add a constructor to the CoOrds class that allows us to specify the initial values for the data members: C#

Copy Code

// A constructor with two arguments: public CoOrds(int x, int y) { this.x = x; this.y = y; } This allows CoOrd objects to be created with default or specific initial values, like this: C#

Copy Code

CoOrds p1 = new CoOrds(); CoOrds p2 = new CoOrds(5, 3); If a class does not have a default constructor, one is automatically generated and default values are used to initialize the object fields, for example, an int is initialized to 0. For more information on default values, see Default Values Table (C# Reference). Therefore, because the CoOrds class default constructor initializes all data members to zero, it can be removed altogether without changing how the class works. A complete example using multiple constructors is provided in Example 1 later in this topic, and an example of an automatically generated constructor is provided in Example 2. Instance constructors can also be used to call the instance constructors of base classes. The class constructor can invoke the constructor of the base class through the initializer, as follows: C#

Copy Code

class Circle : Shape { public Circle(double radius) : base(radius, 0) { } } In this example, the Circle class passes values representing radius and height to the constructor provided by Shape from which Circle is derived. A complete example using Shape and Circle appears in this topic as Example 3. Example 1 The following example demonstrates a class with two class constructors, one without arguments and one with two arguments. C# class CoOrds { public int x, y; // Default constructor: public CoOrds() { x = 0; y = 0; } // A constructor with two arguments: public CoOrds(int x, int y)

Copy Code

{ this.x = x; this.y = y; } // Override the ToString method: public override string ToString() { return (System.String.Format("({0},{1})", x, y)); } } class MainClass { static void Main() { CoOrds p1 = new CoOrds(); CoOrds p2 = new CoOrds(5, 3); // Display the results using the overriden ToString method: System.Console.WriteLine("CoOrds #1 at {0}", p1); System.Console.WriteLine("CoOrds #2 at {0}", p2); } } Output CoOrds #1 at (0,0) CoOrds #2 at (5,3) Example 2 In this example, the class Person does not have any constructors, in which case, a default constructor is automatically provided and the fields are initialized to their default values. C#

Copy Code

public class Person { public int age; public string name; } class TestPerson { static void Main() { Person p = new Person(); System.Console.Write("Name: {0}, Age: {1}", p.name, p.age); } } Output Name: , Age: 0 Notice that the default value of age is 0 and the default value of name is null. For more information on default values, see Default Values Table (C# Reference). Example 3 The following example demonstrates using the base class initializer. The Circle class is derived from the general class Shape, and the Cylinder class is derived from the Circle class. The constructor on each derived class is using its base class initializer. C#

Copy Code

abstract class Shape { public const double pi = System.Math.PI; protected double x, y; public Shape(double x, double y) { this.x = x; this.y = y; } public abstract double Area(); } class Circle : Shape { public Circle(double radius) : base(radius, 0) { } public override double Area() { return pi * x * x; } } class Cylinder : Circle { public Cylinder(double radius, double height) : base(radius) { y = height; } public override double Area() { return (2 * base.Area()) + (2 * pi * x * y); } } class TestShapes { static void Main() { double radius = 2.5; double height = 3.0; Circle ring = new Circle(radius); Cylinder tube = new Cylinder(radius, height); System.Console.WriteLine("Area of the circle = {0:F2}", ring.Area()); System.Console.WriteLine("Area of the cylinder = {0:F2}", tube.Area()); } } Output Area of the circle = 19.63 Area of the cylinder = 86.39 For more examples on invoking the base class constructors, see virtual (C# Reference), override (C# Reference), and

.NET Framework Class Library System Namespace Collapse All Expand All

The System namespace contains fundamental classes and base classes that define commonly-used value and reference data types, events and event handlers, interfaces, attributes, and processing exceptions. Other classes provide services supporting data type conversion, method parameter manipulation, mathematics, remote and local program invocation, application environment management, and supervision of managed and unmanaged applications. Classes Class

Description

AccessViolationException

The exception that is thrown when there is an attempt to read or write protected memory.

ActivationContext

Identifies the activation context for the current application. This class cannot be inherited.

Activator

Contains methods to create types of objects locally or remotely, or obtain references to existing remote objects. This class cannot be inherited.

AppDomain

Represents an application domain, which is an isolated environment where applications execute. This class cannot be inherited.

AppDomainManager

Provides a managed equivalent of an unmanaged host.

AppDomainSetup

Represents assembly binding information that can be added to an instance of AppDomain.

AppDomainUnloadedException

The exception that is thrown when an attempt is made to access an unloaded application domain.

ApplicationException

The exception that is thrown when a non-fatal application error occurs.

ApplicationId

Contains information used to uniquely identify an application. This class cannot be inherited.

ApplicationIdentity

Provides the ability to uniquely identify a manifest-activated application. This class cannot be inherited.

ArgumentException

The exception that is thrown when one of the arguments provided to a method is not valid.

ArgumentNullException

The exception that is thrown when a null reference (Nothing in Visual Basic) is passed to a method that does not accept it as a valid argument.

ArgumentOutOfRangeException

The exception that is thrown when the value of an argument is outside the allowable range of values as defined by the invoked method.

ArithmeticException

The exception that is thrown for errors in an arithmetic, casting, or conversion operation.

Array

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

ArrayTypeMismatchException

The exception that is thrown when an attempt is made to store an element of the wrong type within an array.

AssemblyLoadEventArgs

Provides data for the AssemblyLoad event.

Attribute

Represents the base class for custom attributes.

AttributeUsageAttribute

Specifies the usage of another attribute class. This class cannot be inherited.

BadImageFormatException

The exception that is thrown when the file image of a DLL or an executable program is invalid.

BitConverter

Converts base data types to an array of bytes, and an array of bytes to base data types.

Buffer

Manipulates arrays of primitive types.

CannotUnloadAppDomainException

The exception that is thrown when an attempt to unload an application domain fails.

CharEnumerator

Supports iterating over a String object and reading its individual characters. This class cannot be inherited.

CLSCompliantAttribute

Indicates whether a program element is compliant with the Common Language Specification (CLS). This class cannot be inherited.

Console

Represents the standard input, output, and error streams for console applications. This class cannot be inherited.

ConsoleCancelEventArgs

Provides data for the Console.CancelKeyPress event. This class cannot be inherited.

ContextBoundObject

Defines the base class for all context-bound classes.

ContextMarshalException

The exception that is thrown when an attempt to marshal an object across a context boundary fails.

ContextStaticAttribute

Indicates that the value of a static field is unique for a particular context.

Convert

Converts a base data type to another base data type.

DataMisalignedException

The exception that is thrown when a unit of data is read from or written to an address that is not a multiple of the data size. This class cannot be inherited.

DBNull

Represents a null value.

Delegate

Represents a delegate, which is a data structure that refers to a static method or to a class instance and an instance method of that class.

DivideByZeroException

The exception that is thrown when there is an attempt to divide an integral or decimal value by zero.

DllNotFoundException

The exception that is thrown when a DLL specified in a DLL import cannot be found.

DuplicateWaitObjectException

The exception that is thrown when an object appears more than once in an array of synchronization objects.

EntryPointNotFoundException

The exception that is thrown when an attempt to load a class fails due to the absence of an entry method.

Environment

Provides information about, and means to manipulate, the current environment and platform. This class cannot be inherited.

EventArgs

EventArgs is the base class for classes containing event data.

Exception

Represents errors that occur during application execution.

ExecutionEngineException

The exception that is thrown when there is an internal error in the execution engine of the common language runtime. This class cannot be inherited.

FieldAccessException

The exception that is thrown when there is an invalid attempt to access a private or protected field inside a class.

FileStyleUriParser

A customizable parser based on the File scheme.

FlagsAttribute

Indicates that an enumeration can be treated as a bit field; that is, a set of flags.

FormatException

The exception that is thrown when the format of an argument does not meet the parameter specifications of the invoked method.

FtpStyleUriParser

A customizable parser based on the File Transfer Protocol (FTP) scheme.

GC

Controls the system garbage collector, a service that automatically reclaims unused memory.

GenericUriParser

A customizable parser for a hierarchical URI.

GopherStyleUriParser

A customizable parser based on the Gopher scheme.

HttpStyleUriParser

A customizable parser based on the HTTP scheme.

IndexOutOfRangeException

The exception that is thrown when an attempt is made to access an element of an array with an index that is outside the bounds of the array. This class cannot be inherited.

InsufficientMemoryException

The exception that is thrown when a check for sufficient available memory fails. This class cannot be inherited.

InvalidCastException

The exception that is thrown for invalid casting or explicit conversion.

InvalidOperationException

The exception that is thrown when a method call is invalid for the object's current state.

InvalidProgramException

The exception that is thrown when a program contains invalid Microsoft intermediate language (MSIL) or metadata. Generally this indicates a bug in the compiler that generated the program.

LdapStyleUriParser

A customizable parser based on the Lightweight Directory Access Protocol (LDAP) scheme.

LoaderOptimizationAttribute

Used to set the default loader optimization policy for the main method of an executable application.

LocalDataStoreSlot

Encapsulates a memory slot to store local data. This class cannot be inherited.

MarshalByRefObject

Enables access to objects across application domain boundaries in applications that support remoting.

Math

Provides constants and static methods for trigonometric, logarithmic, and other common mathematical functions.

MemberAccessException

The exception that is thrown when an attempt to access a class member fails.

MethodAccessException

The exception that is thrown when there is an invalid attempt to access a private or protected method inside a class.

MissingFieldException

The exception that is thrown when there is an attempt to dynamically access a field that does not exist.

MissingMemberException

The exception that is thrown when there is an attempt to dynamically access a class member that does not exist.

MissingMethodException

The exception that is thrown when there is an attempt to dynamically access a method that does not exist.

MTAThreadAttribute

Indicates that the COM threading model for an application is multithreaded apartment (MTA).

MulticastDelegate

Represents a multicast delegate; that is, a delegate that can have more than one element in its invocation list.

MulticastNotSupportedException

The exception that is thrown when there is an attempt to combine two instances of a non-combinable delegate type unless one of the operands is a null reference (Nothing in Visual Basic). This class cannot be inherited.

NetPipeStyleUriParser

A parser based on the NetPipe scheme for the "Indigo" system.

NetTcpStyleUriParser

A parser based on the NetTcp scheme for the "Indigo" system.

NewsStyleUriParser

A customizable parser based on the news scheme using the Network News Transfer Protocol (NNTP).

NonSerializedAttribute

Indicates that a field of a serializable class should not be serialized. This class cannot be inherited.

NotFiniteNumberException

The exception that is thrown when a floating-point value is positive infinity, negative infinity, or Not-a-Number (NaN).

NotImplementedException

The exception that is thrown when a requested method or operation is not implemented.

NotSupportedException

The exception that is thrown when an invoked method is not supported, or when there is an attempt to read, seek, or write to a stream that does not support the invoked functionality.

Nullable

Supports a value type that can be assigned a null reference (Nothing in Visual Basic) like a reference type. This class cannot be inherited.

NullReferenceException

The exception that is thrown when there is an attempt to dereference a null object reference.

Object

Supports all classes in the .NET Framework class hierarchy and provides low-level services to derived classes. This is the ultimate base class of all classes in the .NET Framework; it is the root of the type hierarchy.

ObjectDisposedException

The exception that is thrown when an operation is performed on a disposed object.

ObsoleteAttribute

Marks the program elements that are no longer in use. This class cannot be inherited.

OperatingSystem

Represents information about an operating system, such as the version and platform identifier. This class cannot be inherited.

OperationCanceledException

The exception that is thrown in a thread upon cancellation of an operation that the thread was executing.

OutOfMemoryException

The exception that is thrown when there is not enough memory to continue the execution of a program.

OverflowException

The exception that is thrown when an arithmetic, casting, or conversion operation in a checked context results in an overflow.

ParamArrayAttribute

Indicates that the method will allow a variable number of arguments in its invocation. This class cannot be inherited.

PlatformNotSupportedException

The exception that is thrown when a feature does not run on a particular platform.

Random

Represents a pseudo-random number generator, a device that produces a sequence of numbers that meet certain statistical requirements for randomness.

RankException

The exception that is thrown when an array with the wrong number of dimensions is passed to a method.

ResolveEventArgs

Provides data for the TypeResolve, ResourceResolve, and AssemblyResolve events.

SerializableAttribute

Indicates that a class can be serialized. This class cannot be inherited.

StackOverflowException

The exception that is thrown when the execution stack overflows by having too many pending method calls. This class cannot be inherited.

STAThreadAttribute

Indicates that the COM threading model for an application is single-threaded apartment (STA).

String

Represents text as a series of Unicode characters.

StringComparer

Represents a string comparison operation that uses specific case and culture-based or ordinal comparison rules.

SystemException

Defines the base class for predefined exceptions in the System namespace.

ThreadStaticAttribute

Indicates that the value of a static field is unique for each thread.

TimeoutException

The exception that is thrown when the time allotted for a process or operation has expired.

TimeZone

Represents a time zone.

Type

Represents type declarations: class types, interface types, array types, value types, enumeration types, type parameters, generic type definitions, and open or closed constructed generic types.

TypeInitializationException

The exception that is thrown as a wrapper around the exception thrown by the class initializer. This class cannot be inherited.

TypeLoadException

The exception that is thrown when type-loading failures occur.

TypeUnloadedException

The exception that is thrown when there is an attempt to access an unloaded class.

UnauthorizedAccessException

The exception that is thrown when the operating system denies access because of an I/O error or a specific type of security error.

UnhandledExceptionEventArgs

Provides data for the event that is raised when there is an exception that is not handled by the application domain.

Uri

Provides an object representation of a uniform resource identifier (URI) and easy access to the parts of the URI.

UriBuilder

Provides a custom constructor for uniform resource identifiers (URIs) and modifies URIs for the Uri class.

UriFormatException

The exception that is thrown when an invalid Uniform Resource Identifier (URI) is detected.

UriParser

Parses a new URI scheme. This is an abstract class.

UriTypeConverter

Converts a String type to a Uri type, and vice versa.

ValueType

Provides the base class for value types.

Version

Represents the version number for a common language runtime assembly. This class cannot be inherited.

WeakReference

Represents a weak reference, which references an object while still allowing that object to be garbage collected.

Interfaces Interface

Description

_AppDomain

Exposes the public members of the System.AppDomain class to unmanaged code.

IAppDomainSetup

Represents assembly binding information that can be added to an instance of AppDomain.

IAsyncResult

Represents the status of an asynchronous operation.

ICloneable

Supports cloning, which creates a new instance of a class with the same value as an existing instance.

IComparable

Defines a generalized comparison method that a value type or class implements to create a type-specific comparison method.

IComparable

Defines a generalized comparison method that a value type or class implements to create a type-specific comparison method for ordering instances.

IConvertible

Defines methods that convert the value of the implementing reference or value type to a common language runtime type that has an equivalent value.

ICustomFormatter

Defines a method that supports custom, user-defined formatting of the value of an object.

IDisposable

Defines a method to release allocated unmanaged resources.

IEquatable

Defines a generalized method that a value type or class implements to create a type-specific method for determining equality of instances.

IFormatProvider

Provides a mechanism for retrieving an object to control formatting.

IFormattable

Provides functionality to format the value of an object into a string representation.

IServiceProvider

Defines a mechanism for retrieving a service object; that is, an object that provides custom support to other objects.

Structures Structure

Description

ArgIterator

Represents a variable-length argument list; that is, the parameters of a function that takes a variable number of

arguments. ArraySegment

Delimits a section of a one-dimensional array.

Boolean

Represents a Boolean value.

Byte

Represents an 8-bit unsigned integer.

Char

Represents a Unicode character.

ConsoleKeyInfo

Describes the console key that was pressed, including the character represented by the console key and the state of the SHIFT, ALT, and CTRL modifier keys.

DateTime

Represents an instant in time, typically expressed as a date and time of day.

Decimal

Represents a decimal number.

Double

Represents a double-precision floating point number.

Enum

Provides the base class for enumerations.

Guid

Represents a globally unique identifier (GUID).

Int16

Represents a 16-bit signed integer.

Int32

Represents a 32-bit signed integer.

Int64

Represents a 64-bit signed integer.

IntPtr

A platform-specific type that is used to represent a pointer or a handle.

ModuleHandle

Represents a runtime handle for a module.

Nullable

Represents an object whose underlying type is a value type that can also be assigned a null reference (Nothing in Visual Basic) like a reference type.

RuntimeArgumentHandle

References a variable-length argument list.

RuntimeFieldHandle

Represents a field using an internal metadata token.

RuntimeMethodHandle

RuntimeMethodHandle is a handle to the internal metadata representation of a method.

RuntimeTypeHandle

Represents a type using an internal metadata token.

SByte

Represents an 8-bit signed integer.

Single

Represents a single-precision floating point number.

TimeSpan

Represents a time interval.

TypedReference

Describes objects that contain both a managed pointer to a location and a runtime representation of the type that may be stored at that location.

UInt16

Represents a 16-bit unsigned integer.

UInt32

Represents a 32-bit unsigned integer.

UInt64

Represents a 64-bit unsigned integer.

UIntPtr

A platform-specific type that is used to represent a pointer or a handle.

Void

Specifies a return value type for a method that does not return a value.

Delegates Delegate

Description

Action

Represents the method that performs an action on the specified object.

AppDomainInitializer

Represents the callback method to invoke when the application domain is initialized.

AssemblyLoadEventHandler

Represents the method that handles the AssemblyLoad event of an AppDomain.

AsyncCallback

References the callback method to be called when the asynchronous operation is completed.

Comparison

Represents the method that compares two objects of the same type.

ConsoleCancelEventHandler

Represents the method that will handle the CancelKeyPress event of a System.Console.

Converter

Represents a method that converts an object from one type to another type.

CrossAppDomainDelegate

Used by DoCallBack for cross-application domain calls.

EventHandler

Represents the method that will handle an event that has no event data.

EventHandler

Represents the method that will handle an event. The generic type argument specifies the type of the event data generated by the event. This class cannot be inherited.

Predicate

Represents the method that defines a set of criteria and determines whether the specified object meets those criteria.

ResolveEventHandler

Represents the method that handles the TypeResolve, ResourceResolve, and AssemblyResolve events of an AppDomain.

UnhandledExceptionEventHandler

Represents the method that will handle the event raised by an exception that is not handled by the application domain.

Enumerations Enumeration

Description

ActivationContext.ContextForm

Indicates the context for a manifest-activated application.

AppDomainManagerInitializationOptions

Specifies the action that a custom application domain manager takes when initializing a new domain.

AttributeTargets

Specifies the application elements on which it is valid to apply an attribute.

Base64FormattingOptions

Specifies whether relevant System.Convert.ToBase64CharArray and System.Convert.ToBase64String methods insert line breaks in their output.

ConsoleColor

Specifies constants that define foreground and background colors for the console.

ConsoleKey

Specifies the standard keys on a console.

ConsoleModifiers

Represents the SHIFT, ALT, and CTRL modifier keys on a keyboard.

ConsoleSpecialKey

Specifies combinations of modifier and console keys that can interrupt the current process.

DateTimeKind

Specifies whether a DateTime object represents a local time, a Coordinated Universal Time (UTC), or is not specified as either local time or UTC.

DayOfWeek

Specifies the day of the week.

Environment.SpecialFolder

Specifies enumerated constants used to retrieve directory paths to system special folders.

EnvironmentVariableTarget

Specifies the location where an environment variable is stored or retrieved in a set or get operation.

GenericUriParserOptions

Specifies options for a UriParser.

LoaderOptimization

An enumeration used with the LoaderOptimizationAttribute class to specify loader optimizations for an executable.

MidpointRounding

Specifies how mathematical rounding methods should process a number that is midway between two numbers.

PlatformID

Identifies the operating system, or platform, supported by an assembly.

StringComparison

Specifies the culture, case, and sort rules to be used by certain overloads of the String.Compare and String.Equals methods.

StringSplitOptions

Specifies whether applicable System.String.Split method overloads include or omit empty substrings from the return value.

TypeCode

Specifies the type of an object.

UriComponents

Specifies the parts of a Uri.

UriFormat

Controls how URI information is escaped.

UriHostNameType

Defines host name types for the Uri.CheckHostName method.

UriKind

Defines the kinds of Uris for the Uri.IsWellFormedUriString and several System.Uri methods.

UriPartial

Defines the parts of a URI for the Uri.GetLeftPart method.

Send comments about this topic to Microsoft. Passing parameters Parameters are means of passing values to a method.The syntax of passing parameter in C# is [modifiers] DataType ParameterName There are four different ways of passing parameters to a method in C#.The four different types of parameters are 1. Value 2. Out 3. Ref 4. Params 1.Value parameters This is the default parameter type in C#.If the parameter does not have any modifier it is "value" parameter by default.When we use "value" parameters the actual value is passed to the function,which means changes made to the parameter is local to the function and is not passed back to the calling part. using System; class ParameterTest { static void Mymethod(int Param1) { Param1=100; } static void Main() { int Myvalue=5; MyMethod(Myvalue); Console.WriteLine(Myvalue); }

} Output of the above program would be 5.Eventhough the value of the parameter Param1 is changed within MyMethod it is not passed back to the calling part since value parameters are input only. 2.Out parameters "out" parameters are output only parameters meaning they can only passback a value from a function.We create a "out" parameter by preceding the parameter data type with the out modifier. When ever a "out" parameter is passed only an unassigned reference is passed to the function. using System; class ParameterTest { static void Mymethod(out int Param1) { Param1=100; } static void Main() { int Myvalue=5; MyMethod(Myvalue); Console.WriteLine(out Myvalue); } } Output of the above program would be 100 since the value of the "out" parameter is passed back to the calling part. Note The modifier "out" should precede the parameter being passed even in the calling part. "out" parameters cannot be used within the function before assigning a value to it. A value should be assigned to the "out" parameter before the method returns. 3.Ref parameters "ref" parameters are input/output parameters meaning they can be used for passing a value to a function as well as to get back a value from a function.We create a "ref" parameter by preceding the parameter data type with the ref modifier. When ever a "ref" parameter is passed a reference is passed to the function. using System; class ParameterTest { static void Mymethod(ref int Param1) { Param1=Param1 + 100; } static void Main() { int Myvalue=5; MyMethod(Myvalue); Console.WriteLine(ref Myvalue); } } Output of the above program would be 105 since the "ref" parameter acts as both input and output. Note The modifier "ref" should precede the parameter being passed even in the calling part. "ref" parameters should be assigned a value before using it to call a method. 4.Params parameters "params" parameters is a very useful feature in C#. "params" parameter are used when a variable number of arguments need to be passed.The "params" should be a single dimensional or a jagged array. using System; class ParameterTest { static int Sum(params int[] Param1) { int val=0; foreach(int P in Param1) { val=val+P; } return val; } static void Main() {

Console.WriteLine(Sum(1,2,3)); Console.WriteLine(Sum(1,2,3,4,5)); } } Output of the above program would be 6 and 15. Note The value passed for a "params" parameter can be either comma separated value list or a single dimensional array. "params" parameters are input only.

Second def

Output Parameters & Parameter Arrays Output parameters Like reference parameters, output parameters don't create a new storage location, but use the storage location of the variable specified on the invocation. Output parameters need the out modifier as part of both the declaration and the invocation - that means it's always clear when you're passing something as an output parameter. Output parameters are very similar to reference parameters. The only differences are:

• • •

The variable specified on the invocation doesn't need to have been assigned a value before it is passed to the function member. If the function member completes normally, the variable is considered to be assigned afterwards (so you can then "read" it). The parameter is considered initially unassigned (in other words, you must assign it a value before you can "read" it in the function member). The parameter must be assigned a value before the function member completes normally.

Here is some example code showing this, with an int parameter (int is a value type, but if you understood reference parameters properly, you should be able to see what the behaviour for reference types is): void Foo (out int x) { // Can't read x here - it's considered unassigned // Assignment - this must happen before the method can complete normally x = 10; // The value of x can now be read: int a = x; } ... // Declare a variable but don't assign a value to it int y; // Pass it in as an output parameter, even though its value is unassigned Foo (out y); // It's now assigned a value, so we can write it out: Console.WriteLine (y); Output: 10 Parameter arrays Parameter arrays allow a variable number of arguments to be passed into a function member. The definition of the parameter has to include the params modifier, but the use of the parameter has no such keyword. A parameter array has to come at the end of the list of parameters, and must be a singledimensional array. When using the function member, any number of parameters (including none) may appear in the invocation, so long as the parameters are each compatible with the type of the parameter array. Alternatively, a single array may be passed, in which case the parameter acts just as a normal value parameter. For example:

void ShowNumbers (params int[] numbers) { foreach (int x in numbers) { Console.Write (x+" "); } Console.WriteLine(); } ... int[] x = {1, 2, 3}; ShowNumbers (x); ShowNumbers (4, 5); Output: 12345 In the first invocation, the variable x is passed by value, as it's just an array. In the second invocation, a new array of ints is created containing the two values specified, and a reference to this array is passed. Mini-glossary Some informal definitions and summaries of terms: Function member A function member is a method, property, event, indexer, user-defined operator, instance constructor, static constructor, or destructor. Output parameter A parameter very similar to a reference parameter, but with different definite assignment rules. Reference parameter (pass-by-reference semantics) A parameter which shares the storage location of the variable used in the function member invocation. As they share the same storage location, they always have the same value (so changing the parameter value changes the invocation variable value). Reference type Type where the value of a variable/expression of that type is a reference to an object rather than the object itself. Storage location A portion of memory holding the value of a variable. Value parameter (the default semantics, which are pass-by-value) A value parameter that has its own storage location, and thus its own value. The initial value is the value of the expression used in the function member invocation. Value type Type where the value of a variable/expression of that type is the object data itself. Variable Name associated with a storage location and type. (Usually a single variable is associated with a storage location. The exceptions are for reference and output parameters.) Third Using ref and out Parameter: When we pass a parameter as ref to a method, the method refers to the same variable and changes made will affect the actual variable.Even the variable passed as out parameter is similar to ref, but there are few implementation differences when you use it in C# . Argument passed as ref must be initialized before it is passed to the method, where as in case of out its is not necessary,but after a call to the method as an out parameter the variable must be initialized. When to use ref and out parameter. out parameter can be used when we want to return more than one value from a method. IMPORTANT NOTE : We now know what are ref and out parameters, but these are only for C#(these are only understood by csc Compiler) when looking inside the IL Code there is no difference whether you use ref or out parameters. The implementation of ref and out parameter in IL Code is same. When Calling a method and in the method signature after the datatype of the parameter a & sign is used, indicating the address of the variable.

Source Code: RefOut.cs using System; class RefOut { public static void Main(String [] args) { int a = 0,b,c=0,d=0; Console.WriteLine("a is normal parameter will not affect the changes after the function call"); Console.WriteLine("b is out parameter will affect the changes after the function call but not necessary to initialize the variable b but should be initialized in the function ParamTest "); Console.WriteLine("c is ref parameter will affect the changes after the function call and is compulsory to initialize the variable c before calling the function ParamTest"); Console.WriteLine("d is used to store the return value"); d=ParamTest(a,out b,ref c); Console.WriteLine("a = {0}", a); Console.WriteLine("b = {0}", b); Console.WriteLine("c = {0}", c); Console.WriteLine("d = {0}", d); } public static int ParamTest(int a, out int b, ref int c) { a=10; b=20; c=30; return 40; } } Fourth When we are coding a function, we should use out parameter, when we're returning value to it, but we don't need that parameter to be initialized, so that parameter purpose is to accept value from inside the function, for example ( this is not likely, but only for an example ): void Reset ( out int x ) { x=0; }

We should use ref parameter, when we're returning value to it, but we also need that parameter to be initialized, I think the proper example for this is Swap function: void Swap ( ref int x, ref int y ) { int temp ; temp = x ; x=y; y = temp ;

}

Common language runtime (CLR) routines

In DB2(R), a common language runtime (CLR) routine is an external routine created by executing a CREATE PROCEDURE or CREATE FUNCTION statement that references a .NET assembly as its external code body.

The following terms are important in the context of CLR routines:

.NET Framework A Microsoft(R) application development environment comprised of the CLR and .NET Framework class library designed to provide a consistent programming environment for developing and integrating code pieces. Common language runtime (CLR) The runtime interpreter for all .NET Framework applications. intermediate language (IL) Type of compiled byte-code interpreted by the .NET Framework CLR. Source code from all .NET compatible languages compiles to IL byte-code. assembly A file that contains IL byte-code. This can either be a library or an executable.

Fifth Preamble: what is a reference type? In .NET (and therefore C#) there are two main sorts of type: reference types and value types. They act differently, and a lot of confusion about parameter passing is really down to people not properly understanding the difference between them. Here's a quick explanation: A reference type is a type which has as its value a reference to the appropriate data rather than the data itself. For instance, consider the following code: StringBuilder sb = new StringBuilder(); (I have used StringBuilder as a random example of a reference type - there's nothing special about it.) Here, we declare a variable sb, create a new StringBuilder object, and assign to sb a reference to the object. The value of sb is not the object itself, it's the reference. Assignment involving reference types is simple - the value which is assigned is the value of the expression/variable - i.e. the reference. This is demonstrated further in this example: StringBuilder first = new StringBuilder(); StringBuilder second = first; Here we declare a variable first, create a new StringBuilder object, and assign to first a reference to the object. We then assign to second the value of first. This means that they both refer to the same object. They are still, however, independent variables themselves. Changing the value of first will not change the value of second - although while their values are still references to the same object, any changes made to the object through the first variable will be visible through the second variable. Here's a demonstration of that: StringBuilder first = new StringBuilder(); StringBuilder second = first;

first.Append ("hello"); first = null; Console.WriteLine (second); (Download sample code) Output:

using System; using System.Text; public class Example1 { public static void Main (string[] args) { StringBuilder first = new StringBuilder(); StringBuilder second = first; first.Append ("hello"); first = null; Console.WriteLine (second); } }

hello Here, we declare a variable first, create a new StringBuilder object, and assign to first a reference to the object. We then assign to second the value of first. We then call the Append method on this object via the reference held in the first variable. After this, we set the first variable to null (a value which doesn't refer to any object). Finally, we print out the results of calling the ToString method on the StringBuilder object via the reference held in the second variable. hello is displayed, demonstrating that even though the value of first has changed, the data within the object it used to refer to hasn't - and second still refers to that object. Class types, interface types, delegate types and array types are all reference types. Further preamble: what is a value type? While reference types have a layer of indirection between the variable and the real data, value types don't. Variables of a value type directly contain the data. Assignment of a value type involves the actual data being copied. Take a simple struct, for example: public struct IntHolder { public int i; } Wherever there is a variable of type IntHolder, the value of that variable contains all the data - in this case, the single integer value. An assignment copies the value, as demonstrated here: IntHolder first = new IntHolder(); first.i=5; IntHolder second = first; first.i=6; Console.WriteLine (second.i); (Download sample code) Output:

using System; using System.Text; public class Example2 { struct IntHolder { public int i; } public static void Main (string[] args) { IntHolder first = new IntHolder(); first.i=5; IntHolder second = first; first.i=6; Console.WriteLine (second.i); } }

5 Here, second.i has the value 5, because that's the value first.i has when the assignment second=first occurs - the values in second are independent of the values in first apart from when the assignment takes place. Simple types (such as float, int, char), enum types and struct types are all value types. Note that many types (such as string) appear in some ways to be value types, but in fact are reference types. These are known as immutable types. This means that once an instance has been constructed, it can't be changed. This allows a reference type to act similarly to a value type in some ways - in particular, if you hold a reference to an immutable object, you can feel comfortable in returning it from a method or passing it to another method, safe in the knowledge that it won't be changed behind your back. This is why, for instance, the string.Replace doesn't change the string it is called on, but returns a new instance with the new string data in - if the original string were changed, any other variables holding a reference to the string would see the change, which is very rarely what is desired. Constrast this with a mutable (changeable) type such as ArrayList - if a method returns the ArrayList reference stored in an instance variable, the calling code could then add items to the list without the instance having any say about it, which is usually a problem. Having said that immutable reference types act like value types, they are not value types, and shouldn't be thought of as actually being value types. For more information about value types, reference types, and where the data for each is stored in memory, please see my other article about the subject. Checking you understand the preamble... What would you expect to see from the code above if the declaration of the IntHolder type was as a class instead of a struct? If you don't understand why the output would be 6, please re-read both preambles and mail me if it's still not clear - if you don't get it, it's my fault, not yours, and I need to improve this page. If you do understand it, parameter passing becomes very easy to understand - read on. The different kinds of parameters There are four different kinds of parameters in C#: value parameters (the default), reference parameters (which use the ref modifier), output parameters (which use the out modifier), and parameter arrays (which use the params modifier). You can use any of them with both value and reference types. When you hear the words "reference" or "value" used (or use them yourself) you should be very clear in your own mind whether you mean that a parameter is a reference or value parameter, or whether you mean that the type involved is a reference or value type. If you can keep the two ideas separated, they're very simple. Value parameters By default, parameters are value parameters. This means that a new storage location is created for the variable in the function member declaration, and it starts off with the value that you specify in the function member invocation. If you change that value, that doesn't alter any variables involved in the invocation. For instance, if we have:

void Foo (StringBuilder x) { x = null; } ... StringBuilder y = new StringBuilder(); y.Append ("hello"); Foo (y); Console.WriteLine (y==null); (Download sample code)

using System; using System.Text; public class Example3 { // Note that Foo is declared static here just // to make the sample app simple, so we don't // need to instantiate the example class. This // has no bearing on the parameter passing // discussed static void Foo (StringBuilder x) { x = null; } public static void Main (string[] args) { StringBuilder y = new StringBuilder(); y.Append ("hello"); Foo (y); Console.WriteLine (y==null); } }

Output: False The value of y isn't changed just because x is set to null. Remember though that the value of a reference type variable is the reference - if two reference type variables refer to the same object, then changes to the data in that object will be seen via both variables. For example: void Foo (StringBuilder x) { x.Append (" world"); } ... StringBuilder y = new StringBuilder(); y.Append ("hello"); Foo (y); Console.WriteLine (y); (Download sample code)

using System; using System.Text; public class Example4 { // Note that Foo is declared static here just // to make the sample app simple, so we don't // need to instantiate the example class. This // has no bearing on the parameter passing // discussed static void Foo (StringBuilder x) { x.Append (" world"); } public static void Main (string[] args) { StringBuilder y = new StringBuilder(); y.Append ("hello"); Foo (y); Console.WriteLine (y); } }

Output: hello world After calling Foo, the StringBuilder object that y refers to contains "hello world", as in Foo the data " world" was appended to that object via the reference held in x. Now consider what happens when value types are passed by value. As I said before, the value of a value type variable is the data itself. Using the previous definition of the struct IntHolder, let's write some code similar to the above: void Foo (IntHolder x) { x.i=10; } ... IntHolder y = new IntHolder(); y.i=5; Foo (y); Console.WriteLine (y.i); (Download sample code) using System; using System.Text; public class Example5 { struct IntHolder { public int i; } // Note that Foo is declared static here just // to make the sample app simple, so we don't // need to instantiate the example class. This // has no bearing on the parameter passing

// discussed static void Foo (IntHolder x) { x.i=10; } public static void Main (string[] args) { IntHolder y = new IntHolder(); y.i=5; Foo (y); Console.WriteLine (y.i); } }

Output: 5 When Foo is called, x starts off as a struct with value i=5. Its i value is then changed to 10. Foo knows nothing about the variable y, and after the method completes, the value in y will be exactly the same as it was before (i.e. 5). As we did earlier, check that you understand what would happen if IntHolder was declared as a class instead of a struct. You should understand why y.i would be 10 after calling Foo in that case. Reference parameters Reference parameters don't pass the values of the variables used in the function member invocation - they use the variables themselves. Rather than creating a new storage location for the variable in the function member declaration, the same storage location is used, so the value of the variable in the function member and the value of the reference parameter will always be the same. Reference parameters need the ref modifier as part of both the declaration and the invocation - that means it's always clear when you're passing something by reference. Let's look at our previous examples, just changing the parameter to be a reference parameter: void Foo (ref StringBuilder x) { x = null; } ... StringBuilder y = new StringBuilder(); y.Append ("hello"); Foo (ref y); Console.WriteLine (y==null); (Download sample code) using System; using System.Text; public class Example6 { // Note that Foo is declared static here just // to make the sample app simple, so we don't // need to instantiate the example class. This // has no bearing on the parameter passing // discussed static void Foo (ref StringBuilder x) { x = null; }

public static void Main (string[] args) { StringBuilder y = new StringBuilder(); y.Append ("hello"); Foo (ref y); Console.WriteLine (y==null); } }

Output: True Here, because a reference to y is passed rather than its value, changes to the value of parameter x are immediately reflected in y. In the above example, y ends up being null. Compare this with the result of the same code without the ref modifiers. Now consider the struct code we had earlier, but using reference parameters: void Foo (ref IntHolder x) { x.i=10; } ... IntHolder y = new IntHolder(); y.i=5; Foo (ref y); Console.WriteLine (y.i); (Download sample code) using System; using System.Text; public class Example7 { struct IntHolder { public int i; } // Note that Foo is declared static here just // to make the sample app simple, so we don't // need to instantiate the example class. This // has no bearing on the parameter passing // discussed static void Foo (ref IntHolder x) { x.i=10; } public static void Main (string[] args) { IntHolder y = new IntHolder(); y.i=5; Foo (ref y); Console.WriteLine (y.i); } }

Output: 10 The two variables are sharing a storage location, so changes to x are also visible through y, so y.i has the value 10 at the end of this code.

Sidenote: what is the difference between passing a value object by reference and a reference object by value? You may have noticed that the last example, passing a struct by reference, had the same effect in this code as passing a class by value. This doesn't mean that they're the same thing, however. Consider the following code: void Foo (??? IntHolder x) { x = new IntHolder(); } ... IntHolder y = new IntHolder(); y.i=5; Foo (??? y);

In the case where IntHolder is a struct (i.e. a value type) and the parameter is a reference parameter (i.e. replace ??? with ref above), y ends up being a new IntHolder value - i.e. y.i is 0. In the case where IntHolder is a class (i.e. a reference type) and the parameter is a value parameter (i.e. remove ??? above), the value of y isn't changed - it's a reference to the same object it was before the function member call. This difference is absolutely crucial to understanding parameter passing in C#, and is why I believe it is highly confusing to say that objects are passed by reference by default instead of the correct statement that object references are passed by value by default. Output parameters Like reference parameters, output parameters don't create a new storage location, but use the storage location of the variable specified on the invocation. Output parameters need the out modifier as part of both the declaration and the invocation - that means it's always clear when you're passing something as an output parameter. Output parameters are very similar to reference parameters. The only differences are:

• • •

The variable specified on the invocation doesn't need to have been assigned a value before it is passed to the function member. If the function member completes normally, the variable is considered to be assigned afterwards (so you can then "read" it). The parameter is considered initially unassigned (in other words, you must assign it a value before you can "read" it in the function member). The parameter must be assigned a value before the function member completes normally.

Here is some example code showing this, with an int parameter (int is a value type, but if you understood reference parameters properly, you should be able to see what the behaviour for reference types is): void Foo (out int x) { // Can't read x here - it's considered unassigned // Assignment - this must happen before the method can complete normally x = 10; // The value of x can now be read: int a = x; } ...

// Declare a variable but don't assign a value to it int y; // Pass it in as an output parameter, even though its value is unassigned Foo (out y); // It's now assigned a value, so we can write it out: Console.WriteLine (y); (Download sample code) using System; using System.Text; public class Example8 { static void Foo (out int x) { // Can't read x here - it's considered unassigned // Assignment - this must happen before the method can complete normally x = 10; // The value of x can now be read: int a = x; } public static void Main (string[] args) { // Declare a variable but don't assign a value to it int y; // Pass it in as an output parameter, even though its value is unassigned Foo (out y); // It's now assigned a value, so we can write it out: Console.WriteLine (y); } }

Output: 10 Parameter arrays Parameter arrays allow a variable number of arguments to be passed into a function member. The definition of the parameter has to include the params modifier, but the use of the parameter has no such keyword. A parameter array has to come at the end of the list of parameters, and must be a singledimensional array. When using the function member, any number of parameters (including none) may appear in the invocation, so long as the parameters are each compatible with the type of the parameter array. Alternatively, a single array may be passed, in which case the parameter acts just as a normal value parameter. For example: void ShowNumbers (params int[] numbers) { foreach (int x in numbers) { Console.Write (x+" "); } Console.WriteLine(); } ...

int[] x = {1, 2, 3}; ShowNumbers (x); ShowNumbers (4, 5); (Download sample code) using System; using System.Text; public class Example9 { // Note that ShowNumbers is declared static here just // to make the sample app simple, so we don't // need to instantiate the example class. This // has no bearing on the parameter passing // discussed static void ShowNumbers (params int[] numbers) { foreach (int x in numbers) { Console.Write (x+" "); } Console.WriteLine(); } public static void Main (string[] args) { int[] x = {1, 2, 3}; ShowNumbers (x); ShowNumbers (4, 5); } }

Output: 123 45 In the first invocation, the variable x is passed by value, as it's just an array. In the second invocation, a new array of ints is created containing the two values specified, and a reference to this array is passed. Mini-glossary Some informal definitions and summaries of terms: Function member A function member is a method, property, event, indexer, user-defined operator, instance constructor, static constructor, or destructor. Output parameter A parameter very similar to a reference parameter, but with different definite assignment rules. Reference parameter (pass-by-reference semantics) A parameter which shares the storage location of the variable used in the function member invocation. As they share the same storage location, they always have the same value (so changing the parameter value changes the invocation variable value). Reference type Type where the value of a variable/expression of that type is a reference to an object rather than the object itself. Storage location A portion of memory holding the value of a variable. Value parameter (the default semantics, which are pass-by-value) A value parameter that has its own storage location, and thus its own value. The initial value is the value of the expression used in the function member invocation. Value type Type where the value of a variable/expression of that type is the object data itself.

Variable Name associated with a storage location and type. (Usually a single variable is associated with a storage location. The exceptions are for reference and output parameters.) Enumeratos An enumeration (enum) is a special form of value type, which inherits from System.Enum and supplies alternate names for the values of an underlying primitive type. An enumeration type has a name, an underlying type, and a set of fields. The underlying type must be one of the built-in signed or unsigned integer types (such as Byte, Int32, or UInt64). The fields are static literal fields, each of which represents a constant. The language you are using assigns a specific value of the underlying type to each field. The same value can be assigned to multiple fields. When this occurs, the language marks one of the values as the primary enumeration value for purposes of reflection and string conversion. The boxing rules that apply to value types also apply to enumerations. The general form of an enumeration declaration is as follows. <modifier> enum <enum_name> { // Enumeration list } For example: enum Months { jan, feb, mar, apr } By default the first enumerator has the value of zero and the value of each successive enumerator is increased by 1. For example in the above case the value jan is 0, feb is 1 and so on. Remember that the modifier can be private, public, protected or internal. In C# enums, it is possible to override the default values. For example: enum Months { jan = 10, feb = 20, mar = 30, apr=40 } The underlying type specifies how much storage is allocated for each enumerator. However an explicit cast is needed to convert from unum type to integral types. This is why the enum types are type safe in C#. For example: int x = Months.jan; is not a valid statement in C#. int x = (int) Months.jan; is a valid statement. The underlying type of an enumerator can be changed as follows. enum Months : long { jan,feb, mar, apr } Two more enum members can have the same value as follows. enum Months { jan = 1, feb = 1, mar, apr } All the enum members are explicitly static and so they can be accessed only with the type and not with the instances. A complete example is shown below. using System;

enum Months : long { jan = 10,feb = 20,mar } class MyClient { public static void Main() { long x = (long)Months.jan; long y = (long)Months.feb; long z = (long)Months.mar; Console.WriteLine("JANUARY={0},FEbriary = {1},March={2}",x,y,z); } } The following are the restrictions apply to an enum type in C# 1. 2. 3.

They can't define their own methods. They can't implement interfaces. They can't define properties or indexers.

The use of enum type is superior to the use of integer constants, because the use of enum makes the code more readable and self-documenting.

C# Language Reference enum (C# Reference) The enum keyword is used to declare an enumeration, a distinct type consisting of a set of named constants called the enumerator list. Every enumeration type has an underlying type, which can be any integral type except char. The default underlying type of the enumeration elements is int. By default, the first enumerator has the value 0, and the value of each successive enumerator is increased by 1. For example: Copy Code enum Days {Sat, Sun, Mon, Tue, Wed, Thu, Fri}; In this enumeration, Sat is 0, Sun is 1, Mon is 2, and so forth. Enumerators can have initializers to override the default values. For example: Copy Code enum Days {Sat=1, Sun, Mon, Tue, Wed, Thu, Fri}; In this enumeration, the sequence of elements is forced to start from 1 instead of 0. A variable of type Days can be assigned any value in the range of the underlying type; the values are not limited to the named constants. The default value of an enum E is the value produced by the expression (E)0.

Note An enumerator may not contain white space in its name. The underlying type specifies how much storage is allocated for each enumerator. However, an explicit cast is needed to convert from enum type to an integral type. For example, the following statement assigns the enumerator Sun to a variable of the type int using a cast to convert from enum to int: Copy Code

int x = (int)Days.Sun; When you apply System.FlagsAttribute to an enumeration that contains some elements combined with a bitwise OR operation, you will notice that the attribute affects the behavior of the enum when used with some tools. You can notice these changes when using tools such as the Console class methods, the Expression Evaluator, and so forth. (See example 3). Robust Programming

Assigning additional values new versions of enums, or changing the values of the enum members in a new version, can cause problems for dependant source code. It is often the case that enum values are used in switch statements, and if additional elements have been added to the enum type, the test for default values can return true unexpectedly. If other developers will be using your code, it is important to provide guidelines on how their code should react if new elements are added to any enum types. Example

In this example, an enumeration, Days, is declared. Two enumerators are explicitly converted to integer and assigned to integer variables. Copy Code // keyword_enum.cs // enum initialization: using System; public class EnumTest { enum Days {Sat=1, Sun, Mon, Tue, Wed, Thu, Fri};

static void Main() { int x = (int)Days.Sun; int y = (int)Days.Fri; Console.WriteLine("Sun = {0}", x); Console.WriteLine("Fri = {0}", y); } } Output Sun = 2 Fri = 7

In this example, the base-type option is used to declare an enum whose members are of the type long. Notice that even though the underlying type of the enumeration is long, the enumeration members must still be explicitly converted to type long using a cast. Copy Code // keyword_enum2.cs // Using long enumerators using System; public class EnumTest { enum Range :long {Max = 2147483648L, Min = 255L}; static void Main() { long x = (long)Range.Max; long y = (long)Range.Min; Console.WriteLine("Max = {0}", x); Console.WriteLine("Min = {0}", y); } } Output Max = 2147483648 Min = 255 The following code example illustrates the use and effect of the System.FlagsAttribute attribute on an enum declaration. Copy Code // enumFlags.cs // Using the FlagsAttribute on enumerations. using System;

[Flags] public enum CarOptions { SunRoof = 0x01, Spoiler = 0x02, FogLights = 0x04,

TintedWindows = 0x08, }

class FlagTest { static void Main() { CarOptions options = CarOptions.SunRoof | CarOptions.FogLights; Console.WriteLine(options); Console.WriteLine((int)options); } } Output SunRoof, FogLights 5

enum The enum keyword is used to declare an enumeration, a distinct type consisting of a set of named constants called the enumerator list. Every enumeration type has an underlying type, which can be any integral type except char. This declaration takes the following form::

[attributes] [modifiers] enum identifier [:base-type] {enumerator-list} [;] where: attributes (Optional) Additional declarative information. For more information on attributes and attribute classes, see 17. Attributes. modifiers (Optional) The allowed modifiers are new and the four access modifiers. identifier The enum name. base-type (Optional) The underlying type that specifies the storage allocated for each enumerator. It can be one of the integral types except char. The default is int. enumerator-list The enumerators' identifiers separated by commas, optionally including a value assignment. Remarks The default underlying type of the enumeration elements is int. By default, the first enumerator has the value 0, and the value of each successive enumerator is increased by 1. For example:

Copy Code enum Days {Sat, Sun, Mon, Tue, Wed, Thu, Fri}; In this enumeration, Sat is 0, Sun is 1, Mon is 2, and so forth. Enumerators can have initializers to override the default values. For example: Copy Code enum Days {Sat=1, Sun, Mon, Tue, Wed, Thu, Fri}; In this enumeration, the sequence of elements is forced to start from 1 instead of 0. The default value of an enum E is the value produced by the expression (E)0. The underlying type specifies how much storage is allocated for each enumerator. However, an explicit cast is needed to convert from enum type to an integral type. For example, the following statement assigns the enumerator Sun to a variable of the type int using a cast to convert from enum to int: Copy Code int x = (int) Days.Sun; For more information on enumeration types, see 14. Enums. Example 1 In this example, an enumeration, Days, is declared. Two enumerators are explicitly converted to int and assigned to int variables. Copy Code // keyword_enum.cs // enum initialization: using System; public class EnumTest { enum Days {Sat=1, Sun, Mon, Tue, Wed, Thu, Fri};

public static void Main() { int x = (int) Days.Sun; int y = (int) Days.Fri; Console.WriteLine("Sun = {0}", x); Console.WriteLine("Fri = {0}", y); } } Output

Copy Code Sun = 2 Fri = 7 Notice that if you remove the initializer from Sat=1, the result will be: Copy Code Sun = 1 Fri = 6 Example 2 In this example, the base-type option is used to declare an enum whose members are of the type long. Notice that even though the underlying type of the enumeration is long, the enumeration members must still be explicitly converted to type long using a cast. Copy Code // keyword_enum2.cs // Using long enumerators using System; public class EnumTest { enum Range :long {Max = 2147483648L, Min = 255L}; public static void Main() { long x = (long) Range.Max; long y = (long) Range.Min; Console.WriteLine("Max = {0}", x); Console.WriteLine("Min = {0}", y); } } Output Copy Code Max = 2147483648 Min = 255

Definition: "EXCEPTION IS A RUNTIME ERROR WHICH ARISES BECAUSE OF ABNORMAL CONDITION IN A CODE SEQUENCE. " In C# Exception is a class in the system namespace. An object of an exception is that describe the exceptional conditions occur in a code That means, we are catching an exception, creating an object of it, and then throwing it. C# supports exceptions in a very much the same way as Java and C++. Before going into detail, I must say the usefulness of knowing and performing exception handling :



They cannot be ignored, as if calling code does not handle the error, it causes program termination.



They do not need to be to be handled at the point where error took place. This makes them very suitable for library or system code, which can signal an error and leave us to handle it



They can be used when passing back a return value cannot be used

Exceptions are handled by using try...catch statements. Code which may give rise to exceptions is enclosed in a try block, which is followed by one or more catch blocks. Well if you don't use try...catch, you could get errors like the following: class A {static void Main() {catch {}}} TEMP.cs(3,5): error CS1003: Syntax error, 'try' expected class A {static void Main() {finally {}}} TEMP.cs(3,5): error CS1003: Syntax error, 'try' expected class A {static void Main() {try {}}} TEMP.cs(6,3): error CS1524: Expected catch or finally The try block contains the code segment expected to raise an exception. This block is executed until an exception is thrown The catch block contains the exception handler. This block catches the exception and executes the code written in the block. If we do not know what kind of exception is going to be thrown we can simply omit the type of exception. We can collect it in Exception object as shown in the following program: int a, b = 0 ; Console.WriteLine( "My program starts " ) ; try { a = 10 / b; } catch ( Exception e ) { Console.WriteLine ( e ) ; } Console.WriteLine ( "Remaining program" ) ; The output of the program is: My program starts System.DivideByZeroException: Attempted to divide by zero. at ConsoleApplication4.Class1.Main(String[] args) in d:\dont delete\c#(c sharp)\swapna\programs\consoleapplication4\ consoleapplication4\class1.cs:line 51 Remaining program The exception 'Divide by zero' was caught, but the execution of the program did not stop. There are a number of exception classes provided by C#, all of which inherit from the System.Exception class. Following are some common exception classes:

• • • •

Exception Class - - Cause SystemException - A failed run-time check;used as a base class for other. AccessException - Failure to access a type member, such as a method or field. ArgumentException - An argument to a method was invalid.

• • • • • • • • • • • • • • • • •

ArgumentNullException - A null argument was passed to a method that doesn't accept it. ArgumentOutOfRangeException - Argument value is out of range. ArithmeticException - Arithmetic over - or underflow has occurred. ArrayTypeMismatchException - Attempt to store the wrong type of object in an array. BadImageFormatException - Image is in the wrong format. CoreException - Base class for exceptions thrown by the runtime. DivideByZeroException - An attempt was made to divide by zero. FormatException - The format of an argument is wrong. IndexOutOfRangeException - An array index is out of bounds. InvalidCastExpression - An attempt was made to cast to an invalid class. InvalidOperationException - A method was called at an invalid time. MissingMemberException - An invalid version of a DLL was accessed. NotFiniteNumberException - A number is not valid. NotSupportedException - Indicates sthat a method is not implemented by a class. NullReferenceException - Attempt to use an unassigned reference. OutOfMemoryException - Not enough memory to continue execution. StackOverflowException - A stack has overflown.

The finally block is used to do all the clean up code. It does not support the error message, but all the code contained in the finally block is executed after the exception is raised. We can use this block along with try...catch and only with catch too. The finally block is executed even if the error is raised. Control is always passed to the finally block regardless of how the try blocks exits. int a, b = 0 ; Console.WriteLine( "My program starts" ) ; try { a = 10 / b; } catch ( InvalidOperationException e ) { Console.WriteLine ( e ) ; } catch ( DivideByZeroException e) { Console.WriteLine ( e ) ; } finally { Console.WriteLine ( "finally" ) ; } Console.WriteLine ( "Remaining program" ) ; The output here is: My program starts System.DivideByZeroException: Attempted to divide by zero. at ConsoleApplication4.Class1.Main(String[] args) in d:\dont delete\c# (c sharp)\swapna\programs\consoleapplication4\ consoleapplication4\class1.cs:line 51 finally Remaining program But then what's the difference? We could have written Console.WriteLine ("finally"); after the catch block, and not write the finally block at all. Writing finally did not make much of a difference. Anyway the code written after catch gets executed. The answer to this is not clear in this program. It will be clear when we see the try-finally and the throw statement.

int a, b = 0 ; Console.WriteLine( "My program starts" ) try { a = 10 / b; } finally { Console.WriteLine ( "finally" ) ; } Console.WriteLine ( "Remaining program" ) ; Here the output is My program starts Exception occurred: System.DivideByZeroException: Attempted to divide by zero.at ConsoleApplication4.Class1. Main(String[] args) in d:\dont delete\c# (c sharp) \swapna\programs\consoleapplication4\consoleapplication4 \class1.cs:line 51 finally Note that "Remaining program" is not printed out. Only "finally" is printed which is written in the finally block. The throw statement throws an exception. A throw statement with an expression throws the exception produced by evaluating the expression. A throw statement with no expression is used in the catch block. It re-throws the exception that is currently being handled by the catch block. int a, b = 0 ; Console.WriteLine( "My program starts" ) ; try { a = 10 / b; } catch ( Exception e) { throw } finally { Console.WriteLine ( "finally" ) ; } This shows that the exception is re-thrown. Whatever is written in finally is executed and the program terminates. Note again that "Remaining program" is not printed.

Exception handling is an in built mechanism in .NET framework to detect and handle run time errors. The .NET framework contains lots of standard exceptions. The exceptions are anomalies that occur during the execution of a program. They can be because of user, logic or system errors. If a user (programmer) do not provide a mechanism to handle these anomalies, the .NET run time environment provide a default mechanism, which terminates the program execution. C# provides three keywords try, catch and finally to do exception handling. The try encloses the statements that might throw an exception whereas catch handles an exception if one exists. The finally can be used for doing any clean up process. The general form try-catch-finally in C# is shown below try { // Statement which can cause an exception. } catch(Type x) { // Statements for handling the exception } finally

{ //Any cleanup code } If any exception occurs inside the try block, the control transfers to the appropriate catch block and later to the finally block. But in C#, both catch and finally blocks are optional. The try block can exist either with one or more catch blocks or a finally block or with both catch and finally blocks. If there is no exception occurred inside the try block, the control directly transfers to finally block. We can say that the statements inside the finally block is executed always. Note that it is an error to transfer control out of a finally block by using break, continue, return or goto. In C#, exceptions are nothing but objects of the type Exception. The Exception is the ultimate base class for any exceptions in C#. The C# itself provides couple of standard exceptions. Or even the user can create their own exception classes, provided that this should inherit from either Exception class or one of the standard derived classes of Exception class like DivideByZeroExcpetion ot ArgumentException etc. Uncaught Exceptions The following program will compile but will show an error during execution. The division by zero is a runtime anomaly and program terminates with an error message. Any uncaught exceptions in the current context propagate to a higher context and looks for an appropriate catch block to handle it. If it can't find any suitable catch blocks, the default mechanism of the .NET runtime will terminate the execution of the entire program. //C#: Exception Handling //Author: [email protected] using System; class MyClient { public static void Main() { int x = 0; int div = 100/x; Console.WriteLine(div); } } The modified form of the above program with exception handling mechanism is as follows. Here we are using the object of the standard exception class DivideByZeroException to handle the exception caused by division by zero. //C#: Exception Handling using System; class MyClient { public static void Main() { int x = 0; int div = 0; try { div = 100/x; Console.WriteLine("This line in not executed"); } catch(DivideByZeroException de) { Console.WriteLine("Exception occured"); } Console.WriteLine("Result is {0}",div); } } In the above case the program do not terminate unexpectedly. Instead the program control passes from the point where exception occurred inside the try block to the catch blocks. If it finds any suitable catch block, executes the statements inside that catch and continues with the normal execution of the program statements. If a finally block is present, the code inside the finally block will get also be executed. //C#: Exception Handling using System; class MyClient { public static void Main() {

int x = 0; int div = 0; try { div = 100/x; Console.WriteLine("Not executed line"); } catch(DivideByZeroException de) { Console.WriteLine("Exception occured"); } finally { Console.WriteLine("Finally Block"); } Console.WriteLine("Result is {0}",div); } } Remember that in C#, the catch block is optional. The following program is perfectly legal in C#. //C#: Exception Handling using System; class MyClient { public static void Main() { int x = 0; int div = 0; try { div = 100/x; Console.WriteLine("Not executed line"); } finally { Console.WriteLine("Finally Block"); } Console.WriteLine("Result is {0}",div); } } But in this case, since there is no exception handling catch block, the execution will get terminated. But before the termination of the program statements inside the finally block will get executed. In C#, a try block must be followed by either a catch or finally block. Multiple Catch Blocks A try block can throw multiple exceptions, which can handle by using multiple catch blocks. Remember that more specialized catch block should come before a generalized one. Otherwise the compiler will show a compilation error. //C#: Exception Handling: Multiple catch using System; class MyClient { public static void Main() { int x = 0; int div = 0; try { div = 100/x; Console.WriteLine("Not executed line"); } catch(DivideByZeroException de) { Console.WriteLine("DivideByZeroException" ); } catch(Exception ee) { Console.WriteLine("Exception" );

} finally { Console.WriteLine("Finally Block"); } Console.WriteLine("Result is {0}",div); } } Catching all Exceptions By providing a catch block without a brackets or arguments, we can catch all exceptions occurred inside a try block. Even we can use a catch block with an Exception type parameter to catch all exceptions happened inside the try block since in C#, all exceptions are directly or indirectly inherited from the Exception class. //C#: Exception Handling: Handling all exceptions using System; class MyClient { public static void Main() { int x = 0; int div = 0; try { div = 100/x; Console.WriteLine("Not executed line"); } catch { Console.WriteLine("oException" ); } Console.WriteLine("Result is {0}",div); } } The following program handles all exception with Exception object. //C#: Exception Handling: Handling all exceptions using System; class MyClient { public static void Main() { int x = 0; int div = 0; try { div = 100/x; Console.WriteLine("Not executed line"); } catch(Exception e) { Console.WriteLine("oException" ); } Console.WriteLine("Result is {0}",div); } } Throwing an Exception In C#, it is possible to throw an exception programmatically. The 'throw' keyword is used for this purpose. The general form of throwing an exception is as follows. throw exception_obj; For example the following statement throw an ArgumentException explicitly. throw new ArgumentException("Exception");

//C#: Exception Handling: using System; class MyClient { public static void Main() { try { throw new DivideByZeroException("Invalid Division"); } catch(DivideByZeroException e) { Console.WriteLine("Exception" ); } Console.WriteLine("LAST STATEMENT"); } } Re-throwing an Exception The exceptions, which we caught inside a catch block, can re-throw to a higher context by using the keyword throw inside the catch block. The following program shows how to do this. //C#: Exception Handling: Handling all exceptions using System; class MyClass { public void Method() { try { int x = 0; int sum = 100/x; } catch(DivideByZeroException e) { throw; } } } class MyClient { public static void Main() { MyClass mc = new MyClass(); try { mc.Method(); } catch(Exception e) { Console.WriteLine("Exception caught here" ); } Console.WriteLine("LAST STATEMENT"); } } Standard Exceptions There are two types of exceptions: exceptions generated by an executing program and exceptions generated by the common language runtime. System.Exception is the base class for all exceptions in C#. Several exception classes inherit from this class including ApplicationException and SystemException. These two classes form the basis for most other runtime exceptions. Other exceptions that derive directly from System.Exception include IOException, WebException etc. The common language runtime throws SystemException. The ApplicationException is thrown by a user program rather than the runtime. The SystemException includes the ExecutionEngineException, StaclOverFlowException etc. It is not recommended that we catch SystemExceptions nor is it good programming practice to throw SystemExceptions in our applications.



System.OutOfMemoryException

• • • • • • •

System.NullReferenceException Syste.InvalidCastException Syste.ArrayTypeMismatchException System.IndexOutOfRangeException System.ArithmeticException System.DevideByZeroException System.OverFlowException

User-defined Exceptions In C#, it is possible to create our own exception class. But Exception must be the ultimate base class for all exceptions in C#. So the user-defined exception classes must inherit from either Exception class or one of its standard derived classes. //C#: Exception Handling: User defined exceptions using System; class MyException : Exception { public MyException(string str) { Console.WriteLine("User defined exception"); } } class MyClient { public static void Main() { try { throw new MyException("RAJESH"); } catch(Exception e) { Console.WriteLine("Exception caught here" + e.ToString()); } Console.WriteLine("LAST STATEMENT"); } } Design Guidelines Exceptions should be used to communicate exceptional conditions. Don't use them to communicate events that are expected, such as reaching the end of a file. If there's a good predefined exception in the System namespace that describes the exception condition-one that will make sense to the users of the class-use that one rather than defining a new exception class, and put specific information in the message. Finally, if code catches an exception that it isn't going to handle, consider whether it should wrap that exception with additional information before re-throwing it. try-catch (C# Reference) The try-catch statement consists of a try block followed by one or more catch clauses, which specify handlers for different exceptions. Remarks

The try block contains the guarded code that may cause the exception. The block is executed until an exception is thrown or it is completed successfully. For example, the following attempt to cast a null object raises the NullReferenceException exception: Copy Code object o2 = null; try {

int i2 = (int)o2; // Error } The catch clause can be used without arguments, in which case it catches any type of exception, and referred to as the general catch clause. It can also take an object argument derived from System.Exception, in which case it handles a specific exception. For example: Copy Code catch (InvalidCastException e) { } It is possible to use more than one specific catch clause in the same try-catch statement. In this case, the order of the catch clauses is important because the catch clauses are examined in order. Catch the more specific exceptions before the less specific ones. A throw statement can be used in the catch block to re-throw the exception, which has been caught by the catch statement. For example: Copy Code catch (InvalidCastException e) { throw (e);

// Rethrowing exception e

} If you want to re-throw the exception currently handled by a parameter-less catch clause, use the throw statement without arguments. For example: Copy Code catch { throw; } When inside a try block, only initialize variables that are declared therein; otherwise, an exception can occur before the execution of the block is completed. For example, in the following code example, the variable x is initialized inside the try block. An attempt to use this variable outside the try block in the Write(x) statement will generate the compiler error: Use of unassigned local variable. Copy Code static void Main() { int x; try {

// Don't initialize this variable here. x = 123; } catch { } // Error: Use of unassigned local variable 'x'. Console.Write(x); } For more information on catch, see try-catch-finally. Example

In this example, the try block contains a call to the method MyMethod() that may cause an exception. The catch clause contains the exception handler that simply displays a message on the screen. When the throw statement is called from inside MyMethod, the system looks for the catch statement and displays the message Exception caught. Copy Code // try_catch_example.cs using System; class MainClass { static void ProcessString(string s) { if (s == null) { throw new ArgumentNullException(); } }

static void Main() { try {

string s = null; ProcessString(s); } catch (Exception e) { Console.WriteLine("{0} Exception caught.", e); } } } Sample Output System.ArgumentNullException: Value cannot be null. at MainClass.Main() Exception caught. In this example, two catch statements are used. The most specific exception, which comes first, is caught. Copy Code // try_catch_ordering_catch_clauses.cs using System; class MainClass { static void ProcessString(string s) { if (s == null) { throw new ArgumentNullException(); } }

static void Main() { try { string s = null; ProcessString(s);

} // Most specific: catch (ArgumentNullException e) { Console.WriteLine("{0} First exception caught.", e); } // Least specific: catch (Exception e) { Console.WriteLine("{0} Second exception caught.", e); } } } Sample Output System.ArgumentNullException: Value cannot be null. at MainClass.Main() First exception caught. Comments

In the preceding example, if you start with the least specific catch clause, you will get the error message:A previous catch clause already catches all exceptions of this or a super type ('System.Exception') However, to catch the least specific exception, replace the throw statement by the following one: throw new Exception();

A common usage of catch and finally together is to obtain and use resources in a try block, deal with exceptional circumstances in a catch block, and release the resources in the finally block. Example Copy Code // try-catch-finally using System; public class EHClass {

public static void Main () { try { Console.WriteLine("Executing the try statement."); throw new NullReferenceException(); }

catch(NullReferenceException e) { Console.WriteLine("{0} Caught exception #1.", e); }

catch { Console.WriteLine("Caught exception #2."); }

finally { Console.WriteLine("Executing finally block."); } } } Output Copy Code Executing the try statement. System.NullReferenceException: Attempted to dereference a null object reference. at EHClass.Main() Caught exception #1. Executing finally block.

using System; public class TryTest { static void Main() { try { Console.WriteLine(”In Try block”); throw new ArgumentException(); } catch(ArgumentException n1) { Console.WriteLine(”Catch Block”); } finally { Console.WriteLine(”Finally Block”); } } } Output: In Try Block Catch Block Finally Block

This chapter divides neatly into two main topics. First, we.ll consider the classes provided by the .NET Framework classes, which meet the lower-level data transfer requirements of the streams-based I/O framework. These classes further divide into stream classes and file system classes.that is, classes that actually represent data streams, and classes that represent file system objects such as files and directories. Then we.ll look at how you can enhance any custom class to allow it to fit seamlessly into the standard I/O framework. This enhancement is based on a standard attribute that marks your class as capable of being serialized. The serialization process is used in conjunction with the streams classes to stream your custom class objects from one place to another.in memory, to a remote location, or to persistent storage. As part of our exploration of the streams framework, we.ll consider the different types of stream, types of file system objects, and potential application environments, including Microsoft Windows.based and Web-based environments. Stream Classes The .NET Framework classes offer a streams-based I/O framework, with the core classes in the System.IO namespace. All classes that represent streams inherit from the Stream class, and the key classes are listed in Table 1. Table 1 - String and WriteLine Format Specifiers Class Stream FileStream MemoryStream BufferedStream

TextReader

StreamReader

Description The abstract base class Stream supports reading and writing bytes. In addition to basic Stream behavior, this class supports random access to files through its Seek method and supports both synchronous and asynchronous operation. A nonbuffered stream whose encapsulated data is directly accessible in memory. This stream has no backing store and might be useful as a temporary buffer. A Stream that adds buffering to another Stream, such as a NetworkStream. (FileStream already has buffering internally, and a MemoryStream doesn't need buffering.) A BufferedStream object can be composed around some types of streams to improve read and write performance. The abstract base class for StreamReader and StringReader objects. While the implementations of the abstract Stream class are designed for byte input and output, the implementations of TextReader are designed for Unicode character output. Reads characters from a Stream, using Encoding to convert characters to and

from bytes. Reads characters from a String. StringReader allows you to treat a String with the same API; thus, your output can be either a Stream in any encoding or a String. TextWriter The abstract base class for StreamWriter and StringWriter objects. While the implementations of the abstract Stream class are designed for byte input and output, the implementations of TextWriter are designed for Unicode character input. StreamWriter Writes characters to a Stream, using Encoding to convert characters to bytes. StringWriter Writes characters to a String. StringWriter allows you to treat a String with the same API; thus, your output can be either a Stream in any encoding or a String. BinaryReader Reads binary data from a stream. BinaryWriter Writes binary data to a stream. Two classes derived from Stream but not listed in Table 1 are offered in other namespaces. The NetworkStream class represents a Stream over a network connection and resides in the System.Net.Sockets namespace, and the CryptoStream class links data streams to cryptographic transformations and resides in the System.Security.Cryptography namespace. StringReader

The design of the Stream class and its derivatives is intended to provide a generic view of data sources and destinations so that the developer can interchangeably use any of these classes without redesigning the application. In general, Stream objects are capable of one or more of the following:

• • •

Reading The transfer of data from a stream into a data structure, such as an array of bytes Writing The transfer of data from a data structure into a stream Seeking The querying and modifying of the current position within a stream

Note that a given stream might not support all these features. For example, NetworkStream objects don't support seeking. You can use the CanRead, CanWrite, and CanSeek properties of Stream and its derived classes to determine precisely which operations a given stream does in fact support.

Abstract Introduction Abstract classes are one of the essential behaviors provided by .NET. Commonly, you would like to make classes that only represent base classes, and don’t want anyone to create objects of these class types. You can make use of abstract classes to implement such functionality in C# using the modifier 'abstract'. An abstract class means that, no object of this class can be instantiated, but can make derivations of this. An example of an abstract class declaration is: abstract class absClass { } An abstract class can contain either abstract methods or non abstract methods. Abstract members do not have any implementation in the abstract class, but the same has to be provided in its derived class. An example of an abstract method: abstract class absClass { public abstract void abstractMethod(); } Also, note that an abstract class does not mean that it should contain abstract members. Even we can have an abstract class only with non abstract members. For example: abstract class absClass { public void NonAbstractMethod()

{ Console.WriteLine("NonAbstract Method"); } } A sample program that explains abstract classes: Collapse using System; namespace abstractSample { //Creating an Abstract Class abstract class absClass { //A Non abstract method public int AddTwoNumbers(int Num1, int Num2) { return Num1 + Num2; } //An abstract method, to be //overridden in derived class public abstract int MultiplyTwoNumbers(int Num1, int Num2); } //A Child Class of absClass class absDerived:absClass { [STAThread] static void Main(string[] args) { //You can create an //instance of the derived class absDerived calculate = new absDerived(); int added = calculate.AddTwoNumbers(10,20); int multiplied = calculate.MultiplyTwoNumbers(10,20); Console.WriteLine("Added : {0}, Multiplied : {1}", added, multiplied); } //using override keyword, //implementing the abstract method //MultiplyTwoNumbers public override int MultiplyTwoNumbers(int Num1, int Num2) { return Num1 * Num2; } } } In the above sample, you can see that the abstract class absClass contains two methods AddTwoNumbers and MultiplyTwoNumbers. AddTwoNumbers is a non-abstract method which contains implementation and MultiplyTwoNumbers is an abstract method that does not contain implementation. The class absDerived is derived from absClass and the MultiplyTwoNumbers is implemented on absDerived. Within the Main, an instance (calculate) of the absDerived is created, and calls AddTwoNumbers and MultiplyTwoNumbers. You can derive an abstract class from another abstract class. In that case, in the child class it is optional to make the implementation of the abstract methods of the parent class. Example //Abstract Class1 abstract class absClass1 { public abstract int AddTwoNumbers(int Num1, int Num2); public abstract int MultiplyTwoNumbers(int Num1, int Num2); }

//Abstract Class2 abstract class absClass2:absClass1 { //Implementing AddTwoNumbers public override int AddTwoNumbers(int Num1, int Num2) { return Num1+Num2; } } //Derived class from absClass2 class absDerived:absClass2 { //Implementing MultiplyTwoNumbers public override int MultiplyTwoNumbers(int Num1, int Num2) { return Num1*Num2; } } In the above example, absClass1 contains two abstract methods AddTwoNumbers and MultiplyTwoNumbers. The AddTwoNumbers is implemented in the derived class absClass2. The class absDerived is derived from absClass2 and the MultiplyTwoNumbers is implemented there. Abstract properties Following is an example of implementing abstract properties in a class. //Abstract Class with abstract properties abstract class absClass { protected int myNumber; public abstract int numbers { get; set; } } class absDerived:absClass { //Implementing abstract properties public override int numbers { get { return myNumber; } set { myNumber = value; } } } In the above example, there is a protected member declared in the abstract class. The get/set properties for the member variable myNumber is defined in the derived class absDerived. Important rules applied to abstract classes An abstract class cannot be a sealed class. I.e. the following declaration is incorrect. //Incorrect abstract sealed class absClass { }

Declaration of abstract methods are only allowed in abstract classes. An abstract method cannot be private. //Incorrect private abstract int MultiplyTwoNumbers(); The access modifier of the abstract method should be same in both the abstract class and its derived class. If you declare an abstract method as protected, it should be protected in its derived class. Otherwise, the compiler will raise an error. An abstract method cannot have the modifier virtual. Because an abstract method is implicitly virtual. //Incorrect public abstract virtual int MultiplyTwoNumbers(); An abstract member cannot be static. //Incorrect publpublic abstract static int MultiplyTwoNumbers(); Abstract class vs. Interface An abstract class can have abstract members as well non abstract members. But in an interface all the members are implicitly abstract and all the members of the interface must override to its derived class. An example of interface: interface iSampleInterface { //All methods are automaticall abstract int AddNumbers(int Num1, int Num2); int MultiplyNumbers(int Num1, int Num2); } Defining an abstract class with abstract members has the same effect to defining an interface. The members of the interface are public with no implementation. Abstract classes can have protected parts, static methods, etc. A class can inherit one or more interfaces, but only one abstract class. Abstract classes can add more functionality without destroying the child classes that were using the old version. In an interface, creation of additional functions will have an effect on its child classes, due to the necessary implementation of interface methods to classes. The selection of interface or abstract class depends on the need and design of your project. You can make an abstract class, interface or combination of both depending on your needs.

A class representing a base class which other types can subclass. A normal, non-abstract class is called a concrete class. An abstract class may contain either or both abstract and concrete methods. (Properties cannot be marked abstract.) As in ordinary inheritance, a type derived from an abstract class inherits all the base type members including any method implementations. But, if any abstract methods are inherited, the class must either declare itself abstract or provide an implementation.

Definition

A C# abstract class is declared with the abstract keyword.

Abstract and Sealed Classes and Class Members (C# Programming Guide)

The abstract keyword enables you to create classes and class members solely for the purpose of inheritance—to define features of derived, non-abstract classes. The sealed keyword enables you to prevent the inheritance of a class or certain class members that were previously marked virtual. For more information, see How to: Define Abstract Properties (C# Programming Guide). Abstract Classes and Class Members Classes can be declared as abstract. This is accomplished by putting the keyword abstract before the keyword class in the class definition. For example: C# Copy Code public abstract class A { // Class members here. } An abstract class cannot be instantiated. The purpose of an abstract class is to provide a common definition of a base class that multiple derived classes can share. For example, a class library may define an abstract class that is used as a parameter to many of its functions, and require programmers using that library to provide their own implementation of the class by creating a derived class. Abstract classes may also define abstract methods. This is accomplished by adding the keyword abstract before the return type of the method. For example: C# Copy Code public abstract class A { public abstract void DoWork(int i); } Abstract methods have no implementation, so the method definition is followed by a semicolon instead of a normal method block. Derived classes of the abstract class must implement all abstract methods. When an abstract class inherits a virtual method from a base class, the abstract class can override the virtual method with an abstract method. For example: C# Copy Code // compile with: /target:library public class D { public virtual void DoWork(int i) { // Original implementation. } }

public abstract class E : D

{ public abstract override void DoWork(int i); }

public class F : E { public override void DoWork(int i) { // New implementation. } } If a virtual method is declared abstract, it is still virtual to any class inheriting from the abstract class. A class inheriting an abstract method cannot access the original implementation of the method—in the previous example, DoWork on class F cannot call DoWork on class D. In this way, an abstract class can force derived classes to provide new method implementations for virtual methods. Sealed Classes and Class Members Classes can be declared as sealed. This is accomplished by putting the keyword sealed before the keyword class in the class definition. For example: C# Copy Code public sealed class D { // Class members here. } A sealed class cannot be used as a base class. For this reason, it cannot also be an abstract class. Sealed classes are primarily used to prevent derivation. Because they can never be used as a base class, some run-time optimizations can make calling sealed class members slightly faster. A class member, method, field, property, or event, on a derived class that is overriding a virtual member of the base class can declare that member as sealed. This negates the virtual aspect of the member for any further derived class. This is accomplished by putting the sealed keyword before the override keyword in the class member declaration. For example: C# Copy Code public class D : C { public sealed override void DoWork() { } }

This is a detailed analysis of Abstract classes and methods in C# with some concrete examples. The keyword abstract can be used with both classes and methods in C# to declare them as abstract. The classes, which we can't initialize, are known as abstract classes. They provide only partial implementations. But another class can inherit from an abstract class and can create their instances. For example, an abstract class with a non-abstract method. using System; abstract class MyAbs { public void NonAbMethod() { Console.WriteLine("Non-Abstract Method"); } } class MyClass : MyAbs { } class MyClient { public static void Main() { //MyAbs mb = new MyAbs();//not possible to create an instance MyClass mc = new MyClass(); mc.NonAbMethod(); // Displays 'Non-Abstract Method' } } An abstract class can contain abstract and non-abstract methods. When a class inherits from an abstract, the derived class must implement all the abstract methods declared in the base class. An abstract method is a method without any method body. They are implicitly virtual in C#. using System; abstract class MyAbs { public void NonAbMethod() { Console.WriteLine("Non-Abstract Method"); } public abstract void AbMethod(); // An abstract method } class MyClass : MyAbs//must implement base class abstract methods { public override void AbMethod() { Console.WriteLine("Abstarct method"); } } class MyClient { public static void Main() { MyClass mc = new MyClass(); mc.NonAbMethod(); mc.AbMethod(); } } But by declaring the derived class also abstract, we can avoid the implementation of all or certain abstract methods. This is what is known as partial implementation of an abstract class. using System; abstract class MyAbs { public abstract void AbMethod1();

public abstract void AbMethod2(); } //not necessary to implement all abstract methods //partial implementation is possible abstract class MyClass1 : MyAbs { public override void AbMethod1() { Console.WriteLine("Abstarct method #1"); } } class MyClass : MyClass1 { public override void AbMethod2() { Console.WriteLine("Abstarct method #2"); } } class MyClient { public static void Main() { MyClass mc = new MyClass(); mc.AbMethod1(); mc.AbMethod2(); } } In C#, an abstract class can inherit from another non-abstract class. In addition to the methods it inherited from the base class, it is possible to add new abstract and non-abstract methods as showing below. using System; class MyClass1 // Non-Abstract class { public void Method1() { Console.WriteLine("Method of a non-abstract class"); } } abstract class MyAbs : MyClass1 // Inherits from an non-abstract class { public abstract void AbMethod1(); } class MyClass : MyAbs//must implement base class abstract methods { public override void AbMethod1() { Console.WriteLine("Abstarct method #1 of MyClass"); } } class MyClient { public static void Main() { MyClass mc = new MyClass(); mc.Method1(); mc.AbMethod1(); } } An abstract class can also implement from an interface. In this case we must provide method body for all methods it implemented from the interface. using System; interface IInterface { void Method1(); } abstract class MyAbs : IInterface {

public void Method1() { Console.WriteLine("Method implemented from the IInterface"); } } class MyClass : MyAbs//must implement base class abstract method { } class MyClient { public static void Main() { MyClass mc = new MyClass(); mc.Method1(); } } } } We can't use the key word abstract along with sealed in C#, since a sealed class can't be abstract. The abstract methods are implicitly virtual and hence they can't mark explicitly virtual in C#. For example using System; abstract class MyAbs { public abstract void AbMethod1(); public abstract void AbMethod2(); } class MyClass1 : MyAbs { public override void AbMethod1(){ Console.WriteLine("Abstarct method #1 of MyClass1"); } public override void AbMethod2() { Console.WriteLine("Abstarct method #2 of MyClass1"); } } class MyClient { public static void Main() { MyAbs ma1 = new MyClass1();// Polymorphism ma1.AbMethod1(); ma1.AbMethod2(); } }

C# Interview Questions This is a list of questions I have gathered from other sources and created myself over a period of time from my experience, many of which I felt where incomplete or simply wrong. I have finally taken the time to go through each question and correct them to the best of my ability. However, please feel free to post feedback to challenge, improve, or suggest new questions. I want to thank those of you that have contributed quality questions and corrections thus far. There are some question in this list that I do not consider to be good questions for an interview. However, they do exist on other lists available on the Internet so I felt compelled to keep them easy access. General Questions

1.

Does C# support multiple-inheritance? No.

2.

Who is a protected class-level variable available to? It is available to any sub-class (a class inheriting this class).

3.

Are private class-level variables inherited? Yes, but they are not accessible. Although they are not visible or accessible via the class interface, they are inherited.

4.

Describe the accessibility modifier “protected internal”. It is available to classes that are within the same assembly and derived from the specified base class.

5.

What’s the top .NET class that everything is derived from? System.Object.

6.

What does the term immutable mean? The data value may not be changed. Note: The variable value may be changed, but the original immutable data value was discarded and a new data value was created in memory.

7.

What’s the difference between System.String and System.Text.StringBuilder classes? System.String is immutable. System.StringBuilder was designed with the purpose of having a mutable string where a variety of operations can be performed.

8.

What’s the advantage of using System.Text.StringBuilder over System.String? StringBuilder is more efficient in cases where there is a large amount of string manipulation. Strings are immutable, so each time a string is changed, a new instance in memory is created.

9.

Can you store multiple data types in System.Array? No.

10. What’s the difference between the System.Array.CopyTo() and System.Array.Clone()? The Clone() method returns a new array (a shallow copy) object containing all the elements in the original array. The CopyTo() method copies the elements into another existing array. Both perform a shallow copy. A shallow copy means the contents (each array element) contains references to the same object as the elements in the original array. A deep copy (which neither of these methods performs) would create a new instance of each element's object, resulting in a different, yet identacle object.

11. How can you sort the elements of the array in descending order? By calling Sort() and then Reverse() methods.

12. What’s the .NET collection class that allows an element to be accessed using a unique key? HashTable.

13. What class is underneath the SortedList class? A sorted HashTable.

14. Will the finally block get executed if an exception has not occurred? Yes.

15. What’s the C# syntax to catch any possible exception? A catch block that catches the exception of type System.Exception. You can also omit the parameter data type in this case and just write catch {}.

16. Can multiple catch blocks be executed for a single try statement? No. Once the proper catch block processed, control is transferred to the finally block (if there are any).

17. Explain the three services model commonly know as a three-tier application. Presentation (UI), Business (logic and underlying code) and Data (from storage or other sources).

Class Questions

1.

What is the syntax to inherit from a class in C#? Place a colon and then the name of the base class. Example: class MyNewClass : MyBaseClass

2.

Can you prevent your class from being inherited by another class? Yes. The keyword “sealed” will prevent the class from being inherited.

3.

Can you allow a class to be inherited, but prevent the method from being over-ridden? Yes. Just leave the class public and make the method sealed.

4.

What’s an abstract class? A class that cannot be instantiated. An abstract class is a class that must be inherited and have the methods overridden. An abstract class is essentially a blueprint for a class without any implementation.

5.

When do you absolutely have to declare a class as abstract? 1. When the class itself is inherited from an abstract class, but not all base abstract methods have been overridden. 2. When at least one of the methods in the class is abstract.

6.

What is an interface class? Interfaces, like classes, define a set of properties, methods, and events. But unlike classes, interfaces do not provide implementation. They are implemented by classes, and defined as separate entities from classes.

7.

Why can’t you specify the accessibility modifier for methods inside the interface? They all must be public, and are therefore public by default.

8.

Can you inherit multiple interfaces? Yes. .NET does support multiple interfaces.

9.

What happens if you inherit multiple interfaces and they have conflicting method names? It’s up to you to implement the method inside your own class, so implementation is left entirely up to you. This might cause a problem on a higherlevel scale if similarly named methods from different interfaces expect different data, but as far as compiler cares you’re okay. To Do: Investigate

10. What’s the difference between an interface and abstract class? In an interface class, all methods are abstract - there is no implementation. In an abstract class some methods can be concrete. In an interface class, no accessibility modifiers are allowed. An abstract class may have accessibility modifiers.

11. What is the difference between a Struct and a Class? Structs are value-type variables and are thus saved on the stack, additional overhead but faster retrieval. Another difference is that structs cannot inherit.

Method and Property Questions

1.

What’s the implicit name of the parameter that gets passed into the set method/property of a class? Value. The data type of the value parameter is defined by whatever data type the property is declared as.

2.

What does the keyword “virtual” declare for a method or property? The method or property can be overridden.

3.

How is method overriding different from method overloading? When overriding a method, you change the behavior of the method for the derived class. Overloading a method simply involves having another method with the same name within the class.

4.

Can you declare an override method to be static if the original method is not static? No. The signature of the virtual method must remain the same. (Note: Only the keyword virtual is changed to keyword override)

5.

What are the different ways a method can be overloaded? Different parameter data types, different number of parameters, different order of parameters.

6.

If a base class has a number of overloaded constructors, and an inheriting class has a number of overloaded constructors; can you enforce a call from an inherited constructor to a specific base constructor? Yes, just place a colon, and then keyword base (parameter list to invoke the appropriate constructor) in the overloaded constructor definition inside the inherited class.

Events and Delegates

1.

What’s a delegate? A delegate object encapsulates a reference to a method.

2.

What’s a multicast delegate? A delegate that has multiple handlers assigned to it. Each assigned handler (method) is called.

XML Documentation Questions

1.

Is XML case-sensitive? Yes.

2.

What’s the difference between // comments, /* */ comments and /// comments? Single-line comments, multi-line comments, and XML documentation comments.

3.

How do you generate documentation from the C# file commented properly with a command-line compiler? Compile it with the /doc switch.

Debugging and Testing Questions

1.

What debugging tools come with the .NET SDK? 1. CorDBG – command-line debugger. To use CorDbg, you must compile the original C# file using the /debug switch. 2. DbgCLR – graphic debugger. Visual Studio .NET uses the DbgCLR.

2.

What does assert() method do? In debug compilation, assert takes in a Boolean condition as a parameter, and shows the error dialog if the condition is false. The program proceeds without any interruption if the condition is true.

3.

What’s the difference between the Debug class and Trace class? Documentation looks the same. Use Debug class for debug builds, use Trace class for both debug and release builds.

4.

Why are there five tracing levels in System.Diagnostics.TraceSwitcher? The tracing dumps can be quite verbose. For applications that are constantly running you run the risk of overloading the machine and the hard drive. Five levels range from None to Verbose, allowing you to fine-tune the tracing activities.

5.

Where is the output of TextWriterTraceListener redirected? To the Console or a text file depending on the parameter passed to the constructor.

6.

How do you debug an ASP.NET Web application? Attach the aspnet_wp.exe process to the DbgClr debugger.

7.

What are three test cases you should go through in unit testing? 1. Positive test cases (correct data, correct output). 2. Negative test cases (broken or missing data, proper handling). 3. Exception test cases (exceptions are thrown and caught properly).

8.

Can you change the value of a variable while debugging a C# application? Yes. If you are debugging via Visual Studio.NET, just go to Immediate window.

ADO.NET and Database Questions

1.

What is the role of the DataReader class in ADO.NET connections? It returns a read-only, forward-only rowset from the data source. A DataReader provides fast access when a forward-only sequential read is needed.

2.

What are advantages and disadvantages of Microsoft-provided data provider classes in ADO.NET? SQLServer.NET data provider is high-speed and robust, but requires SQL Server license purchased from Microsoft. OLE-DB.NET is universal for accessing other sources, like Oracle, DB2, Microsoft Access and Informix. OLE-DB.NET is a .NET layer on top of the OLE layer, so it’s not as fastest and efficient as SqlServer.NET.

3.

What is the wildcard character in SQL? Let’s say you want to query database with LIKE for all employees whose name starts with La. The wildcard character is %, the proper query with LIKE would involve ‘La%’.

4.

Explain ACID rule of thumb for transactions. A transaction must be: 1. Atomic - it is one unit of work and does not dependent on previous and following transactions. 2. Consistent - data is either committed or roll back, no “in-between” case where something has been updated and something hasn’t. 3. Isolated - no transaction sees the intermediate results of the current transaction). 4. Durable - the values persist if the data had been committed even if the system crashes right after.

5.

What connections does Microsoft SQL Server support? Windows Authentication (via Active Directory) and SQL Server authentication (via Microsoft SQL Server username and password).

6.

Between Windows Authentication and SQL Server Authentication, which one is trusted and which one is untrusted? Windows Authentication is trusted because the username and password are checked with the Active Directory, the SQL Server authentication is untrusted, since SQL Server is the only verifier participating in the transaction.

7.

What does the Initial Catalog parameter define in the connection string? The database name to connect to.

8.

What does the Dispose method do with the connection object? Deletes it from the memory. To Do: answer better. The current answer is not entirely correct.

9.

What is a pre-requisite for connection pooling? Multiple processes must agree that they will share the same connection, where every parameter is the same, including the security settings. The connection string must be identical.

Assembly Questions

1.

How is the DLL Hell problem solved in .NET? Assembly versioning allows the application to specify not only the library it needs to run (which was available under Win32), but also the version of the assembly.

2.

What are the ways to deploy an assembly? An MSI installer, a CAB archive, and XCOPY command.

3.

What is a satellite assembly? When you write a multilingual or multi-cultural application in .NET, and want to distribute the core application separately from the localized modules, the localized assemblies that modify the core application are called satellite assemblies.

4.

What namespaces are necessary to create a localized application? System.Globalization and System.Resources.

5.

What is the smallest unit of execution in .NET? an Assembly.

6.

When should you call the garbage collector in .NET? As a good rule, you should not call the garbage collector. However, you could call the garbage collector when you are done using a large object (or set of objects) to force the garbage collector to dispose of those very large objects from memory. However, this is usually not a good practice.

7.

How do you convert a value-type to a reference-type? Use Boxing.

8.

What happens in memory when you Box and Unbox a value-type? Boxing converts a value-type to a reference-type, thus storing the object on the heap. Unboxing converts a reference-type to a value-type, thus storing the value on the stack.

C# Interview Questions This is a list of questions I have gathered from other sources and created myself over a period of time from my experience, many of which I felt where incomplete or simply wrong. I have finally taken the time to go through each question and correct them to the best of my ability. However, please feel free to post feedback to challenge, improve, or suggest new questions. I want to thank those of you that have contributed quality questions and corrections thus far. There are some question in this list that I do not consider to be good questions for an interview. However, they do exist on other lists available on the Internet so I felt compelled to keep them easy access. General Questions

1.

Does C# support multiple-inheritance? No.

2.

Who is a protected class-level variable available to? It is available to any sub-class (a class inheriting this class).

3.

Are private class-level variables inherited? Yes, but they are not accessible. Although they are not visible or accessible via the class interface, they are inherited.

4.

Describe the accessibility modifier “protected internal”. It is available to classes that are within the same assembly and derived from the specified base class.

5.

What’s the top .NET class that everything is derived from? System.Object.

6.

What does the term immutable mean? The data value may not be changed. Note: The variable value may be changed, but the original immutable data value was discarded and a new data value was created in memory.

7.

What’s the difference between System.String and System.Text.StringBuilder classes? System.String is immutable. System.StringBuilder was designed with the purpose of having a mutable string where a variety of operations can be performed.

8.

What’s the advantage of using System.Text.StringBuilder over System.String? StringBuilder is more efficient in cases where there is a large amount of string manipulation. Strings are immutable, so each time a string is changed, a new instance in memory is created.

9.

Can you store multiple data types in System.Array? No.

10. What’s the difference between the System.Array.CopyTo() and System.Array.Clone()? The Clone() method returns a new array (a shallow copy) object containing all the elements in the original array. The CopyTo() method copies the elements into another existing array. Both perform a shallow copy. A shallow copy means the contents (each array element) contains references to the same object as the elements in the original array. A deep copy (which neither of these methods performs) would create a new instance of each element's object, resulting in a different, yet identacle object.

11. How can you sort the elements of the array in descending order? By calling Sort() and then Reverse() methods.

12. What’s the .NET collection class that allows an element to be accessed using a unique key? HashTable.

13. What class is underneath the SortedList class? A sorted HashTable.

14. Will the finally block get executed if an exception has not occurred? Yes.

15. What’s the C# syntax to catch any possible exception? A catch block that catches the exception of type System.Exception. You can also omit the parameter data type in this case and just write catch {}.

16. Can multiple catch blocks be executed for a single try statement? No. Once the proper catch block processed, control is transferred to the finally block (if there are any).

17. Explain the three services model commonly know as a three-tier application. Presentation (UI), Business (logic and underlying code) and Data (from storage or other sources).

Class Questions

1.

What is the syntax to inherit from a class in C#? Place a colon and then the name of the base class. Example: class MyNewClass : MyBaseClass

2.

Can you prevent your class from being inherited by another class? Yes. The keyword “sealed” will prevent the class from being inherited.

3.

Can you allow a class to be inherited, but prevent the method from being over-ridden? Yes. Just leave the class public and make the method sealed.

4.

What’s an abstract class? A class that cannot be instantiated. An abstract class is a class that must be inherited and have the methods overridden. An abstract class is essentially a blueprint for a class without any implementation.

5.

When do you absolutely have to declare a class as abstract? 1. When the class itself is inherited from an abstract class, but not all base abstract methods have been overridden. 2. When at least one of the methods in the class is abstract.

6.

What is an interface class? Interfaces, like classes, define a set of properties, methods, and events. But unlike classes, interfaces do not provide implementation. They are implemented by classes, and defined as separate entities from classes.

7.

Why can’t you specify the accessibility modifier for methods inside the interface? They all must be public, and are therefore public by default.

8.

Can you inherit multiple interfaces? Yes. .NET does support multiple interfaces.

9.

What happens if you inherit multiple interfaces and they have conflicting method names? It’s up to you to implement the method inside your own class, so implementation is left entirely up to you. This might cause a problem on a higherlevel scale if similarly named methods from different interfaces expect different data, but as far as compiler cares you’re okay. To Do: Investigate

10. What’s the difference between an interface and abstract class? In an interface class, all methods are abstract - there is no implementation. In an abstract class some methods can be concrete. In an interface

class, no accessibility modifiers are allowed. An abstract class may have accessibility modifiers.

11. What is the difference between a Struct and a Class? Structs are value-type variables and are thus saved on the stack, additional overhead but faster retrieval. Another difference is that structs cannot inherit.

Method and Property Questions

1.

What’s the implicit name of the parameter that gets passed into the set method/property of a class? Value. The data type of the value parameter is defined by whatever data type the property is declared as.

2.

What does the keyword “virtual” declare for a method or property? The method or property can be overridden.

3.

How is method overriding different from method overloading? When overriding a method, you change the behavior of the method for the derived class. Overloading a method simply involves having another method with the same name within the class.

4.

Can you declare an override method to be static if the original method is not static? No. The signature of the virtual method must remain the same. (Note: Only the keyword virtual is changed to keyword override)

5.

What are the different ways a method can be overloaded? Different parameter data types, different number of parameters, different order of parameters.

6.

If a base class has a number of overloaded constructors, and an inheriting class has a number of overloaded constructors; can you enforce a call from an inherited constructor to a specific base constructor? Yes, just place a colon, and then keyword base (parameter list to invoke the appropriate constructor) in the overloaded constructor definition inside the inherited class.

Events and Delegates

1.

What’s a delegate? A delegate object encapsulates a reference to a method.

2.

What’s a multicast delegate? A delegate that has multiple handlers assigned to it. Each assigned handler (method) is called.

XML Documentation Questions

1.

Is XML case-sensitive? Yes.

2.

What’s the difference between // comments, /* */ comments and /// comments? Single-line comments, multi-line comments, and XML documentation comments.

3.

How do you generate documentation from the C# file commented properly with a command-line compiler? Compile it with the /doc switch.

Debugging and Testing Questions

1.

What debugging tools come with the .NET SDK? 1. CorDBG – command-line debugger. To use CorDbg, you must compile the original C# file using the /debug switch. 2. DbgCLR – graphic debugger. Visual Studio .NET uses the DbgCLR.

2.

What does assert() method do? In debug compilation, assert takes in a Boolean condition as a parameter, and shows the error dialog if the condition is false. The program proceeds without any interruption if the condition is true.

3.

What’s the difference between the Debug class and Trace class? Documentation looks the same. Use Debug class for debug builds, use Trace class for both debug and release builds.

4.

Why are there five tracing levels in System.Diagnostics.TraceSwitcher? The tracing dumps can be quite verbose. For applications that are constantly running you run the risk of overloading the machine and the hard drive. Five levels range from None to Verbose, allowing you to fine-tune the tracing activities.

5.

Where is the output of TextWriterTraceListener redirected? To the Console or a text file depending on the parameter passed to the constructor.

6.

How do you debug an ASP.NET Web application? Attach the aspnet_wp.exe process to the DbgClr debugger.

7.

What are three test cases you should go through in unit testing? 1. Positive test cases (correct data, correct output). 2. Negative test cases (broken or missing data, proper handling). 3. Exception test cases (exceptions are thrown and caught properly).

8.

Can you change the value of a variable while debugging a C# application? Yes. If you are debugging via Visual Studio.NET, just go to Immediate window.

ADO.NET and Database Questions

1.

What is the role of the DataReader class in ADO.NET connections? It returns a read-only, forward-only rowset from the data source. A DataReader provides fast access when a forward-only sequential read is needed.

2.

What are advantages and disadvantages of Microsoft-provided data provider classes in ADO.NET? SQLServer.NET data provider is high-speed and robust, but requires SQL Server license purchased from Microsoft. OLE-DB.NET is universal for accessing other sources, like Oracle, DB2, Microsoft Access and Informix. OLE-DB.NET is a .NET layer on top of the OLE layer, so it’s not as fastest and efficient as SqlServer.NET.

3.

What is the wildcard character in SQL? Let’s say you want to query database with LIKE for all employees whose name starts with La. The wildcard character is %, the proper query with LIKE would involve ‘La%’.

4.

Explain ACID rule of thumb for transactions. A transaction must be: 1. Atomic - it is one unit of work and does not dependent on previous and following transactions. 2. Consistent - data is either committed or roll back, no “in-between” case where something has been updated and something hasn’t. 3. Isolated - no transaction sees the intermediate results of the current transaction). 4. Durable - the values persist if the data had been committed even if the system crashes right after.

5.

What connections does Microsoft SQL Server support? Windows Authentication (via Active Directory) and SQL Server authentication (via Microsoft SQL Server username and password).

6.

Between Windows Authentication and SQL Server Authentication, which one is trusted and which one is untrusted? Windows Authentication is trusted because the username and password are checked with the Active Directory, the SQL Server authentication is untrusted, since SQL Server is the only verifier participating in the transaction.

7.

What does the Initial Catalog parameter define in the connection string? The database name to connect to.

8.

What does the Dispose method do with the connection object? Deletes it from the memory.

To Do: answer better. The current answer is not entirely correct.

9.

What is a pre-requisite for connection pooling? Multiple processes must agree that they will share the same connection, where every parameter is the same, including the security settings. The connection string must be identical.

Assembly Questions

1.

How is the DLL Hell problem solved in .NET? Assembly versioning allows the application to specify not only the library it needs to run (which was available under Win32), but also the version of the assembly.

2.

What are the ways to deploy an assembly? An MSI installer, a CAB archive, and XCOPY command.

3.

What is a satellite assembly? When you write a multilingual or multi-cultural application in .NET, and want to distribute the core application separately from the localized modules, the localized assemblies that modify the core application are called satellite assemblies.

4.

What namespaces are necessary to create a localized application? System.Globalization and System.Resources.

5.

What is the smallest unit of execution in .NET? an Assembly.

6.

When should you call the garbage collector in .NET? As a good rule, you should not call the garbage collector. However, you could call the garbage collector when you are done using a large object (or set of objects) to force the garbage collector to dispose of those very large objects from memory. However, this is usually not a good practice.

7.

How do you convert a value-type to a reference-type? Use Boxing.

8.

What happens in memory when you Box and Unbox a value-type? Boxing converts a value-type to a reference-type, thus storing the object on the heap. Unboxing converts a reference-type to a value-type, thus storing the value on the stack.

Related Documents

Question 1
November 2019 23
Question 1
April 2020 13
Question 1
October 2019 19
Question 1
November 2019 21
Question 1
November 2019 38
Question 1
October 2019 20