C# – Attributes ”; Previous Next An attribute is a declarative tag that is used to convey information to runtime about the behaviors of various elements like classes, methods, structures, enumerators, assemblies etc. in your program. You can add declarative information to a program by using an attribute. A declarative tag is depicted by square ([ ]) brackets placed above the element it is used for. Attributes are used for adding metadata, such as compiler instruction and other information such as comments, description, methods and classes to a program. The .Net Framework provides two types of attributes: the pre-defined attributes and custom built attributes. Specifying an Attribute Syntax for specifying an attribute is as follows − [attribute(positional_parameters, name_parameter = value, …)] element Name of the attribute and its values are specified within the square brackets, before the element to which the attribute is applied. Positional parameters specify the essential information and the name parameters specify the optional information. Predefined Attributes The .Net Framework provides three pre-defined attributes − AttributeUsage Conditional Obsolete AttributeUsage The pre-defined attribute AttributeUsage describes how a custom attribute class can be used. It specifies the types of items to which the attribute can be applied. Syntax for specifying this attribute is as follows − [AttributeUsage ( validon, AllowMultiple = allowmultiple, Inherited = inherited )] Where, The parameter validon specifies the language elements on which the attribute can be placed. It is a combination of the value of an enumerator AttributeTargets. The default value is AttributeTargets.All. The parameter allowmultiple (optional) provides value for the AllowMultiple property of this attribute, a Boolean value. If this is true, the attribute is multiuse. The default is false (single-use). The parameter inherited (optional) provides value for the Inherited property of this attribute, a Boolean value. If it is true, the attribute is inherited by derived classes. The default value is false (not inherited). For example, [AttributeUsage( AttributeTargets.Class | AttributeTargets.Constructor | AttributeTargets.Field | AttributeTargets.Method | AttributeTargets.Property, AllowMultiple = true)] Conditional This predefined attribute marks a conditional method whose execution depends on a specified preprocessing identifier. It causes conditional compilation of method calls, depending on the specified value such as Debug or Trace. For example, it displays the values of the variables while debugging a code. Syntax for specifying this attribute is as follows − [Conditional( conditionalSymbol )] For example, [Conditional(“DEBUG”)] The following example demonstrates the attribute − Live Demo #define DEBUG using System; using System.Diagnostics; public class Myclass { [Conditional(“DEBUG”)] public static void Message(string msg) { Console.WriteLine(msg); } } class Test { static void function1() { Myclass.Message(“In Function 1.”); function2(); } static void function2() { Myclass.Message(“In Function 2.”); } public static void Main() { Myclass.Message(“In Main function.”); function1(); Console.ReadKey(); } } When the above code is compiled and executed, it produces the following result − In Main function In Function 1 In Function 2 Obsolete This predefined attribute marks a program entity that should not be used. It enables you to inform the compiler to discard a particular target element. For example, when a new method is being used in a class and if you still want to retain the old method in the class, you may mark it as obsolete by displaying a message the new method should be used, instead of the old method. Syntax for specifying this attribute is as follows − [Obsolete ( message )] [Obsolete ( message, iserror )] Where, The parameter message, is a string describing the reason why the item is obsolete and what to use instead. The parameter iserror, is a Boolean value. If its value is true, the compiler should treat the use of the item as an error. Default value is false (compiler generates a warning). The following program demonstrates this − using System; public class MyClass { [Obsolete(“Don”t use OldMethod, use NewMethod instead”, true)] static void OldMethod() { Console.WriteLine(“It is the old method”); } static void NewMethod() { Console.WriteLine(“It is the new method”); } public static void Main() { OldMethod(); } } When you try to compile the program, the compiler gives an error message stating − Don”t use OldMethod, use NewMethod instead Creating Custom Attributes The .Net Framework allows creation of custom attributes that can be used to store declarative information and can be retrieved at run-time. This information can be related to any target element depending upon the design criteria and application need. Creating and using custom attributes involve four steps − Declaring a custom attribute Constructing the custom attribute Apply the custom attribute on a target program element Accessing Attributes Through Reflection The Last step involves writing a simple program to read through the metadata to find various notations. Metadata is data about data or information used for describing other data. This program should use reflections for accessing attributes at runtime. This we will discuss in the next chapter. Declaring a Custom Attribute A new custom attribute should is derived from the System.Attribute class. For example, //a custom attribute BugFix to be assigned to a class and its members [AttributeUsage( AttributeTargets.Class | AttributeTargets.Constructor | AttributeTargets.Field | AttributeTargets.Method | AttributeTargets.Property, AllowMultiple = true)] public class DeBugInfo : System.Attribute In the preceding code, we have declared a custom attribute named DeBugInfo. Constructing the Custom Attribute Let us construct a custom attribute named DeBugInfo, which stores the information obtained by debugging any program. Let it store the following information − The code number for the bug Name of the developer who identified the bug Date of last review of the code A string message for storing the developer”s remarks The DeBugInfo class has three private properties for storing the first three information and a public property for storing the message. Hence the bug number, developer”s name, and date of review are the positional parameters of the DeBugInfo class and the message is an optional or named parameter. Each attribute must have at least one constructor. The positional parameters should be passed through the constructor. The following code shows the DeBugInfo class − //a custom attribute BugFix to be
Category: csharp
C# – Unsafe Codes
C# – Unsafe Codes ”; Previous Next C# allows using pointer variables in a function of code block when it is marked by the unsafe modifier. The unsafe code or the unmanaged code is a code block that uses a pointer variable. Note − To execute the programs mentioned in this chapter at codingground, please set compilation option in Project >> Compile Options >> Compilation Command to mcs *.cs -out:main.exe -unsafe” Pointers A pointer is a variable whose value is the address of another variable i.e., the direct address of the memory location. similar to any variable or constant, you must declare a pointer before you can use it to store any variable address. The general form of a pointer declaration is − type *var-name; Following are valid pointer declarations − int *ip; /* pointer to an integer */ double *dp; /* pointer to a double */ float *fp; /* pointer to a float */ char *ch /* pointer to a character */ The following example illustrates use of pointers in C#, using the unsafe modifier − using System; namespace UnsafeCodeApplication { class Program { static unsafe void Main(string[] args) { int var = 20; int* p = &var; Console.WriteLine(“Data is: {0} “, var); Console.WriteLine(“Address is: {0}”, (int)p); Console.ReadKey(); } } } When the above code wass compiled and executed, it produces the following result − Data is: 20 Address is: 99215364 Instead of declaring an entire method as unsafe, you can also declare a part of the code as unsafe. The example in the following section shows this. Retrieving the Data Value Using a Pointer You can retrieve the data stored at the located referenced by the pointer variable, using the ToString() method. The following example demonstrates this − using System; namespace UnsafeCodeApplication { class Program { public static void Main() { unsafe { int var = 20; int* p = &var; Console.WriteLine(“Data is: {0} ” , var); Console.WriteLine(“Data is: {0} ” , p->ToString()); Console.WriteLine(“Address is: {0} ” , (int)p); } Console.ReadKey(); } } } When the above code was compiled and executed, it produces the following result − Data is: 20 Data is: 20 Address is: 77128984 Passing Pointers as Parameters to Methods You can pass a pointer variable to a method as parameter. The following example illustrates this − using System; namespace UnsafeCodeApplication { class TestPointer { public unsafe void swap(int* p, int *q) { int temp = *p; *p = *q; *q = temp; } public unsafe static void Main() { TestPointer p = new TestPointer(); int var1 = 10; int var2 = 20; int* x = &var1; int* y = &var2; Console.WriteLine(“Before Swap: var1:{0}, var2: {1}”, var1, var2); p.swap(x, y); Console.WriteLine(“After Swap: var1:{0}, var2: {1}”, var1, var2); Console.ReadKey(); } } } When the above code is compiled and executed, it produces the following result − Before Swap: var1: 10, var2: 20 After Swap: var1: 20, var2: 10 Accessing Array Elements Using a Pointer In C#, an array name and a pointer to a data type same as the array data, are not the same variable type. For example, int *p and int[] p, are not same type. You can increment the pointer variable p because it is not fixed in memory but an array address is fixed in memory, and you can”t increment that. Therefore, if you need to access an array data using a pointer variable, as we traditionally do in C, or C++ ( please check: C Pointers), you need to fix the pointer using the fixed keyword. The following example demonstrates this − using System; namespace UnsafeCodeApplication { class TestPointer { public unsafe static void Main() { int[] list = {10, 100, 200}; fixed(int *ptr = list) /* let us have array address in pointer */ for ( int i = 0; i < 3; i++) { Console.WriteLine(“Address of list[{0}]={1}”,i,(int)(ptr + i)); Console.WriteLine(“Value of list[{0}]={1}”, i, *(ptr + i)); } Console.ReadKey(); } } } When the above code was compiled and executed, it produces the following result − Address of list[0] = 31627168 Value of list[0] = 10 Address of list[1] = 31627172 Value of list[1] = 100 Address of list[2] = 31627176 Value of list[2] = 200 Compiling Unsafe Code For compiling unsafe code, you have to specify the /unsafe command-line switch with command-line compiler. For example, to compile a program named prog1.cs containing unsafe code, from command line, give the command − csc /unsafe prog1.cs If you are using Visual Studio IDE then you need to enable use of unsafe code in the project properties. To do this − Open project properties by double clicking the properties node in the Solution Explorer. Click on the Build tab. Select the option “Allow unsafe code“. Print Page Previous Next Advertisements ”;
C# – Quick Guide
C# – Quick Guide ”; Previous Next C# – Overview C# is a modern, general-purpose, object-oriented programming language developed by Microsoft and approved by European Computer Manufacturers Association (ECMA) and International Standards Organization (ISO). C# was developed by Anders Hejlsberg and his team during the development of .Net Framework. C# is designed for Common Language Infrastructure (CLI), which consists of the executable code and runtime environment that allows use of various high-level languages on different computer platforms and architectures. The following reasons make C# a widely used professional language − It is a modern, general-purpose programming language It is object oriented. It is component oriented. It is easy to learn. It is a structured language. It produces efficient programs. It can be compiled on a variety of computer platforms. It is a part of .Net Framework. Strong Programming Features of C# Although C# constructs closely follow traditional high-level languages, C and C++ and being an object-oriented programming language. It has strong resemblance with Java, it has numerous strong programming features that make it endearing to a number of programmers worldwide. Following is the list of few important features of C# − Boolean Conditions Automatic Garbage Collection Standard Library Assembly Versioning Properties and Events Delegates and Events Management Easy-to-use Generics Indexers Conditional Compilation Simple Multithreading LINQ and Lambda Expressions Integration with Windows C# – Environment Try it Option Online We have set up the C# Programming environment online, so that you can compile and execute all the available examples online. It gives you confidence in what you are reading and enables you to verify the programs with different options. Feel free to modify any example and execute it online. Try the following example using our online compiler available at CodingGround using System; namespace HelloWorldApplication { class HelloWorld { static void Main(string[] args) { /* my first program in C# */ Console.WriteLine(“Hello World”); Console.ReadKey(); } } } For most of the examples given in this tutorial, you will find a Try it option in our website code sections at the top right corner that will take you to the online compiler. So just make use of it and enjoy your learning. In this chapter, we will discuss the tools required for creating C# programming. We have already mentioned that C# is part of .Net framework and is used for writing .Net applications. Therefore, before discussing the available tools for running a C# program, let us understand how C# relates to the .Net framework. The .Net Framework The .Net framework is a revolutionary platform that helps you to write the following types of applications − Windows applications Web applications Web services The .Net framework applications are multi-platform applications. The framework has been designed in such a way that it can be used from any of the following languages: C#, C++, Visual Basic, Jscript, COBOL, etc. All these languages can access the framework as well as communicate with each other. The .Net framework consists of an enormous library of codes used by the client languages such as C#. Following are some of the components of the .Net framework − Common Language Runtime (CLR) The .Net Framework Class Library Common Language Specification Common Type System Metadata and Assemblies Windows Forms ASP.Net and ASP.Net AJAX ADO.Net Windows Workflow Foundation (WF) Windows Presentation Foundation Windows Communication Foundation (WCF) LINQ For the jobs each of these components perform, please see ASP.Net – Introduction, and for details of each component, please consult Microsoft”s documentation. Integrated Development Environment (IDE) for C# Microsoft provides the following development tools for C# programming − Visual Studio 2010 (VS) Visual C# 2010 Express (VCE) Visual Web Developer The last two are freely available from Microsoft official website. Using these tools, you can write all kinds of C# programs from simple command-line applications to more complex applications. You can also write C# source code files using a basic text editor, like Notepad, and compile the code into assemblies using the command-line compiler, which is again a part of the .NET Framework. Visual C# Express and Visual Web Developer Express edition are trimmed down versions of Visual Studio and has the same appearance. They retain most features of Visual Studio. In this tutorial, we have used Visual C# 2010 Express. You can download it from Microsoft Visual Studio. It gets installed automatically on your machine. Note: You need an active internet connection for installing the express edition. Writing C# Programs on Linux or Mac OS Although the.NET Framework runs on the Windows operating system, there are some alternative versions that work on other operating systems. Mono is an open-source version of the .NET Framework which includes a C# compiler and runs on several operating systems, including various flavors of Linux and Mac OS. Kindly check Go Mono. The stated purpose of Mono is not only to be able to run Microsoft .NET applications cross-platform, but also to bring better development tools for Linux developers. Mono can be run on many operating systems including Android, BSD, iOS, Linux, OS X, Windows, Solaris, and UNIX. C# – Program Structure Before we study basic building blocks of the C# programming language, let us look at a bare minimum C# program structure so that we can take it as a reference in upcoming chapters. Creating Hello World Program A C# program consists of the following parts − Namespace declaration A class Class methods Class attributes A Main method Statements and Expressions Comments Let us look at a simple code that prints the words “Hello World” − using System; namespace HelloWorldApplication { class HelloWorld { static void Main(string[] args) { /* my first program in C# */ Console.WriteLine(“Hello World”); Console.ReadKey(); } } } When this code is compiled and executed, it produces the following result − Hello World Let us look at the various parts of the given program − The first line of the program using System; – the using keyword is used to include the System namespace in the program. A program generally has multiple
C# – Basic Syntax
C# – Basic Syntax ”; Previous Next C# is an object-oriented programming language. In Object-Oriented Programming methodology, a program consists of various objects that interact with each other by means of actions. The actions that an object may take are called methods. Objects of the same kind are said to have the same type or, are said to be in the same class. For example, let us consider a Rectangle object. It has attributes such as length and width. Depending upon the design, it may need ways for accepting the values of these attributes, calculating the area, and displaying details. Let us look at implementation of a Rectangle class and discuss C# basic syntax − Live Demo using System; namespace RectangleApplication { class Rectangle { // member variables double length; double width; public void Acceptdetails() { length = 4.5; width = 3.5; } public double GetArea() { return length * width; } public void Display() { Console.WriteLine(“Length: {0}”, length); Console.WriteLine(“Width: {0}”, width); Console.WriteLine(“Area: {0}”, GetArea()); } } class ExecuteRectangle { static void Main(string[] args) { Rectangle r = new Rectangle(); r.Acceptdetails(); r.Display(); Console.ReadLine(); } } } When the above code is compiled and executed, it produces the following result − Length: 4.5 Width: 3.5 Area: 15.75 The using Keyword The first statement in any C# program is using System; The using keyword is used for including the namespaces in the program. A program can include multiple using statements. The class Keyword The class keyword is used for declaring a class. Comments in C# Comments are used for explaining code. Compilers ignore the comment entries. The multiline comments in C# programs start with /* and terminates with the characters */ as shown below − /* This program demonstrates The basic syntax of C# programming Language */ Single-line comments are indicated by the ”//” symbol. For example, }//end class Rectangle Member Variables Variables are attributes or data members of a class, used for storing data. In the preceding program, the Rectangle class has two member variables named length and width. Member Functions Functions are set of statements that perform a specific task. The member functions of a class are declared within the class. Our sample class Rectangle contains three member functions: AcceptDetails, GetArea and Display. Instantiating a Class In the preceding program, the class ExecuteRectangle contains the Main() method and instantiates the Rectangle class. Identifiers An identifier is a name used to identify a class, variable, function, or any other user-defined item. The basic rules for naming classes in C# are as follows − A name must begin with a letter that could be followed by a sequence of letters, digits (0 – 9) or underscore. The first character in an identifier cannot be a digit. It must not contain any embedded space or symbol such as? – + ! @ # % ^ & * ( ) [ ] { } . ; : ” ” / and . However, an underscore ( _ ) can be used. It should not be a C# keyword. C# Keywords Keywords are reserved words predefined to the C# compiler. These keywords cannot be used as identifiers. However, if you want to use these keywords as identifiers, you may prefix the keyword with the @ character. In C#, some identifiers have special meaning in context of code, such as get and set are called contextual keywords. The following table lists the reserved keywords and contextual keywords in C# − Reserved Keywords abstract as base bool break byte case catch char checked class const continue decimal default delegate do double else enum event explicit extern false finally fixed float for foreach goto if implicit in in (generic modifier) int interface internal is lock long namespace new null object operator out out (generic modifier) override params private protected public readonly ref return sbyte sealed short sizeof stackalloc static string struct switch this throw true try typeof uint ulong unchecked unsafe ushort using virtual void volatile while Contextual Keywords add alias ascending descending dynamic from get global group into join let orderby partial (type) partial (method) remove select set Print Page Previous Next Advertisements ”;
C# – Nullables
C# – Nullables ”; Previous Next C# provides a special data types, the nullable types, to which you can assign normal range of values as well as null values. For example, you can store any value from -2,147,483,648 to 2,147,483,647 or null in a Nullable<Int32> variable. Similarly, you can assign true, false, or null in a Nullable<bool> variable. Syntax for declaring a nullable type is as follows − < data_type> ? <variable_name> = null; The following example demonstrates use of nullable data types − Live Demo using System; namespace CalculatorApplication { class NullablesAtShow { static void Main(string[] args) { int? num1 = null; int? num2 = 45; double? num3 = new double?(); double? num4 = 3.14157; bool? boolval = new bool?(); // display the values Console.WriteLine(“Nullables at Show: {0}, {1}, {2}, {3}”, num1, num2, num3, num4); Console.WriteLine(“A Nullable boolean value: {0}”, boolval); Console.ReadLine(); } } } When the above code is compiled and executed, it produces the following result − Nullables at Show: , 45, , 3.14157 A Nullable boolean value: The Null Coalescing Operator (??) The null coalescing operator is used with the nullable value types and reference types. It is used for converting an operand to the type of another nullable (or not) value type operand, where an implicit conversion is possible. If the value of the first operand is null, then the operator returns the value of the second operand, otherwise it returns the value of the first operand. The following example explains this − Live Demo using System; namespace CalculatorApplication { class NullablesAtShow { static void Main(string[] args) { double? num1 = null; double? num2 = 3.14157; double num3; num3 = num1 ?? 5.34; Console.WriteLine(” Value of num3: {0}”, num3); num3 = num2 ?? 5.34; Console.WriteLine(” Value of num3: {0}”, num3); Console.ReadLine(); } } } When the above code is compiled and executed, it produces the following result − Value of num3: 5.34 Value of num3: 3.14157 Print Page Previous Next Advertisements ”;
C# – Preprocessor Directives
C# – Preprocessor Directives ”; Previous Next The preprocessor directives give instruction to the compiler to preprocess the information before actual compilation starts. All preprocessor directives begin with #, and only white-space characters may appear before a preprocessor directive on a line. Preprocessor directives are not statements, so they do not end with a semicolon (;). C# compiler does not have a separate preprocessor; however, the directives are processed as if there was one. In C# the preprocessor directives are used to help in conditional compilation. Unlike C and C++ directives, they are not used to create macros. A preprocessor directive must be the only instruction on a line. Preprocessor Directives in C# The following table lists the preprocessor directives available in C# − Sr.No. Preprocessor Directive & Description 1 #define It defines a sequence of characters, called symbol. 2 #undef It allows you to undefine a symbol. 3 #if It allows testing a symbol or symbols to see if they evaluate to true. 4 #else It allows to create a compound conditional directive, along with #if. 5 #elif It allows creating a compound conditional directive. 6 #endif Specifies the end of a conditional directive. 7 #line It lets you modify the compiler”s line number and (optionally) the file name output for errors and warnings. 8 #error It allows generating an error from a specific location in your code. 9 #warning It allows generating a level one warning from a specific location in your code. 10 #region It lets you specify a block of code that you can expand or collapse when using the outlining feature of the Visual Studio Code Editor. 11 #endregion It marks the end of a #region block. The #define Preprocessor The #define preprocessor directive creates symbolic constants. #define lets you define a symbol such that, by using the symbol as the expression passed to the #if directive, the expression evaluates to true. Its syntax is as follows − #define symbol The following program illustrates this − Live Demo #define PI using System; namespace PreprocessorDAppl { class Program { static void Main(string[] args) { #if (PI) Console.WriteLine(“PI is defined”); #else Console.WriteLine(“PI is not defined”); #endif Console.ReadKey(); } } } When the above code is compiled and executed, it produces the following result − PI is defined Conditional Directives You can use the #if directive to create a conditional directive. Conditional directives are useful for testing a symbol or symbols to check if they evaluate to true. If they do evaluate to true, the compiler evaluates all the code between the #if and the next directive. Syntax for conditional directive is − #if symbol [operator symbol]… Where, symbol is the name of the symbol you want to test. You can also use true and false or prepend the symbol with the negation operator. The operator symbol is the operator used for evaluating the symbol. Operators could be either of the following − == (equality) != (inequality) && (and) || (or) You can also group symbols and operators with parentheses. Conditional directives are used for compiling code for a debug build or when compiling for a specific configuration. A conditional directive beginning with a #if directive must explicitly be terminated with a #endif directive. The following program demonstrates use of conditional directives − Live Demo #define DEBUG #define VC_V10 using System; public class TestClass { public static void Main() { #if (DEBUG && !VC_V10) Console.WriteLine(“DEBUG is defined”); #elif (!DEBUG && VC_V10) Console.WriteLine(“VC_V10 is defined”); #elif (DEBUG && VC_V10) Console.WriteLine(“DEBUG and VC_V10 are defined”); #else Console.WriteLine(“DEBUG and VC_V10 are not defined”); #endif Console.ReadKey(); } } When the above code is compiled and executed, it produces the following result − DEBUG and VC_V10 are defined Print Page Previous Next Advertisements ”;
C# – Questions and Answers
C# Questions and Answers ”; Previous Next C# Questions and Answers has been designed with a special intention of helping students and professionals preparing for various Certification Exams and Job Interviews. This section provides a useful collection of sample Interview Questions and Multiple Choice Questions (MCQs) and their answers with appropriate explanations. Sr.No. Question/Answers Type 1 C# Interview Questions This section provides a huge collection of C# Interview Questions with their answers hidden in a box to challenge you to have a go at them before discovering the correct answer. 2 C# Online Quiz This section provides a great collection of C# Multiple Choice Questions (MCQs) on a single page along with their correct answers and explanation. If you select the right option, it turns green; else red. 3 C# Online Test If you are preparing to appear for a Java and C# related certification exam, then this section is a must for you. This section simulates a real online test along with a given timer which challenges you to complete the test within a given time-frame. Finally you can check your overall test score and how you fared among millions of other candidates who attended this online test. 4 C# Mock Test This section provides various mock tests that you can download at your local machine and solve offline. Every mock test is supplied with a mock test key to let you verify the final score and grade yourself. Print Page Previous Next Advertisements ”;
C# – File I/O
C# – File I/O ”; Previous Next A file is a collection of data stored in a disk with a specific name and a directory path. When a file is opened for reading or writing, it becomes a stream. The stream is basically the sequence of bytes passing through the communication path. There are two main streams: the input stream and the output stream. The input stream is used for reading data from file (read operation) and the output stream is used for writing into the file (write operation). C# I/O Classes The System.IO namespace has various classes that are used for performing numerous operations with files, such as creating and deleting files, reading from or writing to a file, closing a file etc. The following table shows some commonly used non-abstract classes in the System.IO namespace − Sr.No. I/O Class & Description 1 BinaryReader Reads primitive data from a binary stream. 2 BinaryWriter Writes primitive data in binary format. 3 BufferedStream A temporary storage for a stream of bytes. 4 Directory Helps in manipulating a directory structure. 5 DirectoryInfo Used for performing operations on directories. 6 DriveInfo Provides information for the drives. 7 File Helps in manipulating files. 8 FileInfo Used for performing operations on files. 9 FileStream Used to read from and write to any location in a file. 10 MemoryStream Used for random access to streamed data stored in memory. 11 Path Performs operations on path information. 12 StreamReader Used for reading characters from a byte stream. 13 StreamWriter Is used for writing characters to a stream. 14 StringReader Is used for reading from a string buffer. 15 StringWriter Is used for writing into a string buffer. The FileStream Class The FileStream class in the System.IO namespace helps in reading from, writing to and closing files. This class derives from the abstract class Stream. You need to create a FileStream object to create a new file or open an existing file. The syntax for creating a FileStream object is as follows − FileStream <object_name> = new FileStream( <file_name>, <FileMode Enumerator>, <FileAccess Enumerator>, <FileShare Enumerator>); For example, we create a FileStream object F for reading a file named sample.txt as shown − FileStream F = new FileStream(“sample.txt”, FileMode.Open, FileAccess.Read, FileShare.Read); Sr.No. Parameter & Description 1 FileMode The FileMode enumerator defines various methods for opening files. The members of the FileMode enumerator are − Append − It opens an existing file and puts cursor at the end of file, or creates the file, if the file does not exist. Create − It creates a new file. CreateNew − It specifies to the operating system, that it should create a new file. Open − It opens an existing file. OpenOrCreate − It specifies to the operating system that it should open a file if it exists, otherwise it should create a new file. Truncate − It opens an existing file and truncates its size to zero bytes. 2 FileAccess FileAccess enumerators have members: Read, ReadWrite and Write. 3 FileShare FileShare enumerators have the following members − Inheritable − It allows a file handle to pass inheritance to the child processes None − It declines sharing of the current file Read − It allows opening the file for readin. ReadWrite − It allows opening the file for reading and writing Write − It allows opening the file for writing Example The following program demonstrates use of the FileStream class − Live Demo using System; using System.IO; namespace FileIOApplication { class Program { static void Main(string[] args) { FileStream F = new FileStream(“test.dat”, FileMode.OpenOrCreate, FileAccess.ReadWrite); for (int i = 1; i <= 20; i++) { F.WriteByte((byte)i); } F.Position = 0; for (int i = 0; i <= 20; i++) { Console.Write(F.ReadByte() + ” “); } F.Close(); Console.ReadKey(); } } } When the above code is compiled and executed, it produces the following result − 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 -1 Advanced File Operations in C# The preceding example provides simple file operations in C#. However, to utilize the immense powers of C# System.IO classes, you need to know the commonly used properties and methods of these classes. Sr.No. Topic & Description 1 Reading from and Writing into Text files It involves reading from and writing into text files. The StreamReader and StreamWriter class helps to accomplish it. 2 Reading from and Writing into Binary files It involves reading from and writing into binary files. The BinaryReader and BinaryWriter class helps to accomplish this. 3 Manipulating the Windows file system It gives a C# programamer the ability to browse and locate Windows files and directories. Print Page Previous Next Advertisements ”;
C# – Multithreading
C# – Multithreading ”; Previous Next A thread is defined as the execution path of a program. Each thread defines a unique flow of control. If your application involves complicated and time consuming operations, then it is often helpful to set different execution paths or threads, with each thread performing a particular job. Threads are lightweight processes. One common example of use of thread is implementation of concurrent programming by modern operating systems. Use of threads saves wastage of CPU cycle and increase efficiency of an application. So far we wrote the programs where a single thread runs as a single process which is the running instance of the application. However, this way the application can perform one job at a time. To make it execute more than one task at a time, it could be divided into smaller threads. Thread Life Cycle The life cycle of a thread starts when an object of the System.Threading.Thread class is created and ends when the thread is terminated or completes execution. Following are the various states in the life cycle of a thread − The Unstarted State − It is the situation when the instance of the thread is created but the Start method is not called. The Ready State − It is the situation when the thread is ready to run and waiting CPU cycle. The Not Runnable State − A thread is not executable, when Sleep method has been called Wait method has been called Blocked by I/O operations The Dead State − It is the situation when the thread completes execution or is aborted. The Main Thread In C#, the System.Threading.Thread class is used for working with threads. It allows creating and accessing individual threads in a multithreaded application. The first thread to be executed in a process is called the main thread. When a C# program starts execution, the main thread is automatically created. The threads created using the Thread class are called the child threads of the main thread. You can access a thread using the CurrentThread property of the Thread class. The following program demonstrates main thread execution − Live Demo using System; using System.Threading; namespace MultithreadingApplication { class MainThreadProgram { static void Main(string[] args) { Thread th = Thread.CurrentThread; th.Name = “MainThread”; Console.WriteLine(“This is {0}”, th.Name); Console.ReadKey(); } } } When the above code is compiled and executed, it produces the following result − This is MainThread Properties and Methods of the Thread Class The following table shows some most commonly used properties of the Thread class − Sr.No. Property & Description 1 CurrentContext Gets the current context in which the thread is executing. 2 CurrentCulture Gets or sets the culture for the current thread. 3 CurrentPrinciple Gets or sets the thread”s current principal (for role-based security). 4 CurrentThread Gets the currently running thread. 5 CurrentUICulture Gets or sets the current culture used by the Resource Manager to look up culture-specific resources at run-time. 6 ExecutionContext Gets an ExecutionContext object that contains information about the various contexts of the current thread. 7 IsAlive Gets a value indicating the execution status of the current thread. 8 IsBackground Gets or sets a value indicating whether or not a thread is a background thread. 9 IsThreadPoolThread Gets a value indicating whether or not a thread belongs to the managed thread pool. 10 ManagedThreadId Gets a unique identifier for the current managed thread. 11 Name Gets or sets the name of the thread. 12 Priority Gets or sets a value indicating the scheduling priority of a thread. 13 ThreadState Gets a value containing the states of the current thread. The following table shows some of the most commonly used methods of the Thread class − Sr.No. Method & Description 1 public void Abort() Raises a ThreadAbortException in the thread on which it is invoked, to begin the process of terminating the thread. Calling this method usually terminates the thread. 2 public static LocalDataStoreSlot AllocateDataSlot() Allocates an unnamed data slot on all the threads. For better performance, use fields that are marked with the ThreadStaticAttribute attribute instead. 3 public static LocalDataStoreSlot AllocateNamedDataSlot(string name) Allocates a named data slot on all threads. For better performance, use fields that are marked with the ThreadStaticAttribute attribute instead. 4 public static void BeginCriticalRegion() Notifies a host that execution is about to enter a region of code in which the effects of a thread abort or unhandled exception might jeopardize other tasks in the application domain. 5 public static void BeginThreadAffinity() Notifies a host that managed code is about to execute instructions that depend on the identity of the current physical operating system thread. 6 public static void EndCriticalRegion() Notifies a host that execution is about to enter a region of code in which the effects of a thread abort or unhandled exception are limited to the current task. 7 public static void EndThreadAffinity() Notifies a host that managed code has finished executing instructions that depend on the identity of the current physical operating system thread. 8 public static void FreeNamedDataSlot(string name) Eliminates the association between a name and a slot, for all threads in the process. For better performance, use fields that are marked with the ThreadStaticAttribute attribute instead. 9 public static Object GetData(LocalDataStoreSlot slot) Retrieves the value from the specified slot on the current thread, within the current thread”s current domain. For better performance, use fields that are marked with the ThreadStaticAttribute attribute instead. 10 public static AppDomain GetDomain() Returns the current domain in which the current thread is running. 11 public static AppDomain GetDomainID() Returns a unique application domain identifier 12 public static LocalDataStoreSlot GetNamedDataSlot(string name) Looks up a named data slot. For better performance, use fields that are marked with the ThreadStaticAttribute attribute instead. 13 public void Interrupt() Interrupts a thread that is in the WaitSleepJoin thread state. 14 public void Join() Blocks the calling thread until a thread terminates, while continuing to perform standard COM and SendMessage pumping. This method has different overloaded forms. 15 public
C# – Operators
C# – Operators ”; Previous Next An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. C# has rich set of built-in operators and provides the following type of operators − Arithmetic Operators Relational Operators Logical Operators Bitwise Operators Assignment Operators Misc Operators This tutorial explains the arithmetic, relational, logical, bitwise, assignment, and other operators one by one. Arithmetic Operators Following table shows all the arithmetic operators supported by C#. Assume variable A holds 10 and variable B holds 20 then − Show Examples Operator Description Example + Adds two operands A + B = 30 – Subtracts second operand from the first A – B = -10 * Multiplies both operands A * B = 200 / Divides numerator by de-numerator B / A = 2 % Modulus Operator and remainder of after an integer division B % A = 0 ++ Increment operator increases integer value by one A++ = 11 — Decrement operator decreases integer value by one A– = 9 Relational Operators Following table shows all the relational operators supported by C#. Assume variable A holds 10 and variable B holds 20, then − Show Examples Operator Description Example == Checks if the values of two operands are equal or not, if yes then condition becomes true. (A == B) is not true. != Checks if the values of two operands are equal or not, if values are not equal then condition becomes true. (A != B) is true. > Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true. (A > B) is not true. < Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true. (A < B) is true. >= Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true. (A >= B) is not true. <= Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true. (A <= B) is true. Logical Operators Following table shows all the logical operators supported by C#. Assume variable A holds Boolean value true and variable B holds Boolean value false, then − Show Examples Operator Description Example && Called Logical AND operator. If both the operands are non zero then condition becomes true. (A && B) is false. || Called Logical OR Operator. If any of the two operands is non zero then condition becomes true. (A || B) is true. ! Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false. !(A && B) is true. Bitwise Operators Bitwise operator works on bits and perform bit by bit operation. The truth tables for &, |, and ^ are as follows − p q p & q p | q p ^ q 0 0 0 0 0 0 1 0 1 1 1 1 1 1 0 1 0 0 1 1 Assume if A = 60; and B = 13; then in the binary format they are as follows − A = 0011 1100 B = 0000 1101 ——————- A&B = 0000 1100 A|B = 0011 1101 A^B = 0011 0001 ~A = 1100 0011 The Bitwise operators supported by C# are listed in the following table. Assume variable A holds 60 and variable B holds 13, then − Show Examples Operator Description Example & Binary AND Operator copies a bit to the result if it exists in both operands. (A & B) = 12, which is 0000 1100 | Binary OR Operator copies a bit if it exists in either operand. (A | B) = 61, which is 0011 1101 ^ Binary XOR Operator copies the bit if it is set in one operand but not both. (A ^ B) = 49, which is 0011 0001 ~ Binary Ones Complement Operator is unary and has the effect of ”flipping” bits. (~A ) = -61, which is 1100 0011 in 2”s complement due to a signed binary number. << Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand. A << 2 = 240, which is 1111 0000 >> Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand. A >> 2 = 15, which is 0000 1111 Assignment Operators There are following assignment operators supported by C# − Show Examples Operator Description Example = Simple assignment operator, Assigns values from right side operands to left side operand C = A + B assigns value of A + B into C += Add AND assignment operator, It adds right operand to the left operand and assign the result to left operand C += A is equivalent to C = C + A -= Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operand C -= A is equivalent to C = C – A *= Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operand C *= A is equivalent to C = C * A /= Divide AND assignment operator, It divides left operand with the right operand and assign the result to left operand C /= A is equivalent to C = C / A %= Modulus AND assignment operator, It takes modulus using two operands and assign the result to left operand C %= A is equivalent to C = C % A <<= Left shift AND assignment operator C <<= 2 is same as C = C << 2 >>= Right shift AND assignment operator C >>= 2 is same as C = C