Chapter: 1 Introduction to C#.NET

Rate this post
  1. Introduce C# its Features and Applications

Introduce C#

C#’ (pronounced as ‘C sharp’) is a new computer-programming language developed by Microsoft Corporation, USA. C# is a fully object-oriented language like Java and is the first Component-oriented language. It has been designed to support the key features of .NET Framework, the new development platform of Microsoft for building component-based software solutions. It is a simple, efficient, productive and type-safe language derived from the popular C and C++ languages. Although it belongs to the family of C/C++, it is a purely objected-oriented, modern language suitable for developing Web based applications.

image 3

‘C#’ seems a strange name for a modern programming language. Perhaps Microsoft named their new language ‘C sharp’ because they wanted it to be better, smarter and ‘sharper’ than its ancestors C and C++, C# is designed to bring rapid development to C++ programmers without sacrificing the power and control that have been the hallmarks of C and C++, C# is the only language designed especially for the .NET platform which provides tools and services that fully exploit both computing and communications.

Since one of the designers of C# (Anders Hejsberg) was a Java expert, it is natural that many Java features have been incorporated into the design of C#. In fact, in many cases, the C# code may bear a striking resemblance to the functionally equivalent Java code. Unlike C++, both Java and C# promote a one-stop coding approach to code maintenance. They group classes, interfaces and implementations together in one file so that programmers can edit the code more easily.

C# is designed for building robust, reliable and durable components to handle real-world applications. Major highlights of C# are:

  • It is a brand-new language derived from the C/C++ family
  • It simplifies and modernizes C++
  • It is the only component-oriented language available today
  • It is the only language designed for the .NET Framework
  • It is a concise, lean and modern language
  • It has a lean and consistent syntax

C# Features

The language that is designed for both computing and communication is characterised by several key features. They are:

  • Simple
  • Object Oriented
  • Compatible
  • Consistent
  • Modern
  • Versionable

Simple:

C# simplifies C++ by eliminating irksome operators such as ->,:: and pointers. C# treats integer and Boolean data types as two entirely different types. This means that the use of in place of–in if statements will be caught by the compiler.

Object-Oriented

C# is truly object-oriented. It supports all the three tenets of object-oriented systems, namely,

  • Encapsulation
  • Inheritance
  • Polymorphism

Compatible

C# enforces the .NET common language specifications and therefore allows inter-operation with other .NET languages. C# provides support for transparent access to standard COM and OLE Automation. C# also permits interoperation with C-style APIs.

Consistent

C# supports a unified type system which eliminates the problem of varying ranges of integer types. All types are treated as objects and developers can extend the type system simply and easily.

Modern

C# is called a modern language due to a number of features it supports. It supports

  • Automatic garbage collection
  • Modern approach to debugging and
  • Rich intrinsic model for error handling
  • Robust security model
  • Decimal data type for financial applications

Vesionable

Making new versions of software modules work with the existing applications is known as versioning. C# provides support for versioning with the help of new and override keywords. With this support, a programmer can guarantee that his new class library will maintain binary compatibility with the existing client applications.

C# Applications

C# is a new language developed exclusively to suit the features of .NET platform. It can be used for a variety of applications that are supported by the .NET platform:

  • Console applications
  • Windows applications
  • Developing Windows controls
  • Developing ASP.NET projects
  • Creating Web controls
  • Providing Web services

Development of C# .NET

Microsoft Chairman Bill Gates, the architect of many innovative and path-breaking software products during the past two decades, wanted to develop a software platform which will overcome these limitations and enable users to get information anytime and anywhere, using a natural interface. The platform should be a collection of readily available Web services that can be distributed and accessed via standard Internet protocols. He wanted to make the Web both programmable and intelligent. The outcome is a new generation platform called .NET. NET is simply the Microsoft’s vision of ‘software as a service.

image 4

Although the research and development work of .NET platform began in the mid-90s, only during the Microsoft Professional Developers Conference in September 2000, was NET officially announced to the developer community. At the same conference, Microsoft introduced C# as a de facto language of the .NET platform. In fact, they had already used C# to code key modules of the .NET platform. C# has been particularly designed to build software components for .NET and supports key features of .NET natively. They are fairly tightly tied together. In fact, C# compiler is embedded into .NET as shown in Fig.

  1. Introduce the structure of C#

An executable C# program may contain a number coding blocks as shown in Fig. The documentation section consists of a set of comments giving the name of the program, the author, date and other details, which the programmer (or other users) may like to use at a later stage. Comments must explain,

  • Why and what of classes, and the
    • How of algorithms

This would greatly help maintaining the program.

image 5

The using directive section will include all those namespaces that contain classes required by the application. using directives tell the compiler to look in the namespace specified for these unresolved classes.

An interface is similar to a class but contains only abstract members. Interfaces are used when we want to implement the concept of multiple inheritance in a program.

A C# program may contain multiple class definitions. Classes are the primary and essential elements of a C# program. These classes are used to map the objects of real-world problems. The number of classes depends on the complexity of the problem.

Since every C# application program requires a Main method as its starting point, the class containing the Main is the essential part of the program. A simple C# program may contain only this part. The Main method creates objects of various classes and establishes communications between them. On reaching the end of Main, the program terminates and the control passes back to the operating system.

The code below is the basic structure of a C# program.

class SampleOne{

    public static void Main(){

        Console.WriteLine(“C# is Sharper than C++.”);

    }

}

Class Declaration

The first line,

class SampleOne

declares a class, which is an object-oriented construct. As stated earlier, C# is a true object-oriented language and therefore, ‘everything’ must be placed inside a class. class is a keyword and declares that a new class definition follows. SampleOne is a C# identifier that specifies the name of the class to be defined.

The Braces

C# is a block-structured language, meaning code blocks are always enclosed by braces { and }. Therefore, every class definition in C# begins with an opening brace ‘{’ and ends with a corresponding closing brace ‘}’ that appears in the last line of the program.

The Main Method

The third line,

public static void Main()

defines a method named Main. Every C# executable program must include the Main() method in one of the classes. This is the ‘starting point for executing the program. A C# application can have any number of classes but ‘only one’ class can have the Main method to initiate the execution.

  1. public

The keyword public is an access modifier that tells the C# compiler that the Main method is accessible by anyone

  • static

The keyword static declares that the Main method is a global one and can be called without creating an instance of the class. The compiler stores the address of the method as the entry point and uses this information to begin execution before any objects are created.

  • void

The keyword void is a type modifier that states that the Main method does not return any value (but simply prints some text to the screen).

The Output Line

The only executable statement in the program is ,

System.Console.WriteLine(“C# is sharper than C++.”)

This has a striking resemblance to the output statement of Java and similar to the printf() of C or cout<< of C++. Since C# is a pure object-oriented language, every method should be part of an object. The WriteLine method is a static method of the Console class, which is located in the namespace System. This line prints the string C# is sharper than C++ to the screen. The method WriteLine always appends a new-line character to the end of the string. This means, any subsequent output will start on a new line.

Note the semicolon at the end of the statement. Every C# statement must end with a semicolon. And also note that there is no semicolon at the end of the class.

  1. Analyze the variables of C#

A variable is an identifier that denotes a storage location used to store a data value. Unlike constants that remain unchanged during the execution of a program, a variable may take different values at different times during the execution of the program. Every variable has a type that determines what values can be stored in the variable.

A variable name can be chosen by the programmer in a meaningful way so as to reflect what it represents in the program. Some examples of variable names are:

  • Average
  • total_height
  • height
  • classStrength

As mentioned earlier, variable names may consist of alphabets, digits and the underscore (__), subject to the following conditions:

  1. They must not begin with a digit.
  2. Uppercase and lowercase are distinct. This means that the variable Total is not the same as total or TOTAL.
  3. It should not be a keyword.
  4. White space is not allowed.
  5. Variable names can be of any length.

Variables are the names of storage locations. After designing suitable variable names, we must declare them to the compiler. Declaration does three things:

  1. It tells the compiler what the variable name is.
  2. It specifies what type of data the variable will hold.
  3. The place of declaration (in the program) decides the scope of the variable. A variable must be declared before it is used in the program.

A variable can be used to store a value of any data type. The general form of declaration of a variable is:

type   variable1, variable2, ………, variableN;

Example: int count;

   float p1, p2

   char character1;

A variable must be given a value after it has been declared but before it is used in an expression. A simple method of giving value to a variable is through the assignment statement as follows:

 variableName = value;

               or,

type variableName = value;

                        Example:

                                                value2 = 26;

                                                float roll_no = 19;

  1. Describe the Identifiers of C#

Identifiers are programmer-designed tokens. They are used for naming classes, methods, variables, labels, namespaces, interfaces, etc. C# identifiers enforce the following rules:

  • They can have alphabets, digits and underscore characters
  • They must not begin with a digit
  • Upper case and lower-case letters are distinct
  • Keywords in stand-alone mode cannot be used as identifiers

C# permits the use of keywords as identifiers when they are prefixed with the ‘@’ character

  1. Introduce the keywords of C#

Keywords are an essential part of a language definition. They implement specific features of the language. They are reserved, and cannot be used as identifiers except when they are prefaced by the @ character. Below are the lists all the C# keywords:

abstractasbasebool
breakbytecasecatch
charcheckedclassconst
continuedecimaldefaultdelegate
dodoubleelseenum
eventexplicitexternfalse
finallyfixedfloatfor
foreachgotoifimplicit
inin (generic modifier)intinterface
internalislocklong
namespacenewnullobject
operatoroutout (generic modifier)override
paramsprivateprotectedpublic
readonlyrefreturnsbyte
sealedshortsizeofstackalloc
staticstringstructswitch
thisthrowtruetry
typeofuintulongunchecked
unsafeushortusingusing static
voidvolatilewhile
  1. Explain data types in C#

Every variable in C# is associated with a data type. Data types specify the size and type of values that can be stored. C# is a language rich in its data types. The variety available allows the programmer to select the type appropriate to the needs of the application.

image 6

The types in C# are primarily divided into three categories:

  1. Value Type
  2. Reference Type
  3. Pointer
  1. Value types

Value types (which are of fixed length) are stored on the stack, and when a value of a variable is assigned to another variable, the value is actually copied. This means that two identical copies of the value are available in memory.

Int

The int data type can store whole numbers from -2147483648 to 2147483647. In general, and in our tutorial, the int data type is the preferred data type when we create variables with a numeric value.

Example

int myNum = 100000;

Console.WriteLine(myNum);

Long

The long data type can store whole numbers from -9223372036854775808 to 9223372036854775807. This is used when int is not large enough to store the value. Note that you should end the value with an “L”:

Example

long myNum = 15000000000L;

Console.WriteLine(myNum);

Float

The float and double data types can store fractional numbers. Note that you should end the value with an “F” for floats and “D” for doubles:

Example

float myNum = 5.75F;

Console.WriteLine(myNum);

Double

It is 64-bit double-precision floating point type. It has 14 – 15 digit Precision. To initialize a double variable, use the suffix d or D.

Example:

          double d1 = 324.2D;

          Console.WriteLine(d1);

Booleans

A boolean data type is declared with the bool keyword and can only take the values true or false:

Example

bool isCSharpFun = true;

Console.WriteLine(isCSharpFun);   // Outputs True

Characters

The char data type is used to store a single character. The character must be surrounded by single quotes, like ‘A’ or ‘c’:

Example

char myGrade = ‘B’;

Console.WriteLine(myGrade);

                      Strings

The string data type is used to store a sequence of characters (text). String values must be surrounded by double quotes:

Example

string greeting = “Hello World”;

Console.WriteLine(greeting);

                      Decimal Types

The decimal type is a 128-bit data type suitable for financial and monetary calculations. It has 28–29-digit Precision.

Example        

          decimal sa = 72847;

          Console.WriteLine(sa);

  • Reference types

Reference types (which are of variable length) are stored on the heap, and when an assignment between two reference variables occurs, only the reference is copied; the actual value remains in the same memory location. This means that there are two references to a single value.

User-defined reference types refer to those types which we define using predefined types. They include:

  1. Classes
    1. Delegates
    1. Interfaces
    1. Arrays
  • Pointer

A third category of types called pointers is available for use only in unsafe code. Value types and reference types are further classified as predefined and user defined types

  • & (ampersand) is the address operator used to determine the address of a variable.
  • * (asterisk) is indirection operator used to access the value of an address.
  1. State the C# type conversion

Type conversion is converting one type of data to another type. It is also known as Type Casting. Type casting is when you assign a value of one data type to another type.

The process of converting the value of one type (int, float, double, etc.) to another type is known as type conversion.

The process of assigning a smaller type to a larger one is known as widening or promotion and that of assigning a larger type to a smaller one is known as narrowing. Note that narrowing may result in loss of information.

In C#, there are two basic types of type conversion:

  1. Implicit Type Conversions
  2. Explicit Type Conversions            
  1. Implicit Type Conversion

In implicit type conversion, the C# compiler automatically converts one type to another.

Generally, smaller types like int (having less memory size) are automatically converted to larger types like double (having larger memory size).

char -> int -> long -> float -> double

An implicit conversion is also known as automatic type conversion.

Example:

short sa = 26;

       int ah = sa;      // implicit conversion

       float sk = 45232.23;

       double as = sk;      // implicit conversion

Code:

using System;

namespace MyApplication

{

    class Program

    {

        static void Main(string[] args)

        {

            int numInt = 500;

            // get type of numInt

            Type n = numInt.GetType();

            // Implicit Conversion

            double numDouble = numInt;

            // get type of numDouble

            Type n1 = numDouble.GetType();

            // Value before conversion

            Console.WriteLine(“numInt value: ” + numInt);

            Console.WriteLine(“numInt Type: ” + n);

            // Value after conversion

            Console.WriteLine(“numDouble value: ” + numDouble);

            Console.WriteLine(“numDouble Type: ” + n1);

            Console.ReadLine();

        }

    }

}

                        Output:

                                                numInt value: 500

numInt Type: System.Int32

numDouble value: 500

numDouble Type: System.Double

  • Explicit Type Conversion

In explicit type conversion, we explicitly convert one type to another.

Generally, larger types like double (having large memory size) are converted to smaller types like int (having small memory size).

double -> float -> long -> int -> char

                         Explicit casting must be done manually by placing the type in parentheses in front of the value. We can explicitly carry out such conversions using the ‘cast’ operator. The process is known as casting and is done as follows:

type variable1 = (type) variable2;

    Example:

          int m = 50;

byte n = (byte) m;

long x = 1234L;

int y = (int) x;

float f = 50.OF;

long y = (long) f;               

                          Code:

using System;

namespace MyApplication {

  class Program {

    static void Main(string[] args) {

      double numDouble = 1.23;

      // Explicit casting

      int numInt = (int) numDouble; 

      // Value before conversion

      Console.WriteLine(“Original double Value: “+numDouble);

      // Value before conversion

      Console.WriteLine(“Converted int Value: “+numInt);

      Console.ReadLine();

    }

  }

}

Output:

                                Original double value: 1.23

Converted int value: 1

  1. Introduce to C# operators

An operator is a symbol that tells the computer to perform certain mathematical or logical manipulations. Operators are used in programs to manipulate data and variables. They usually form a part of mathematical or logical expressions.

C# supports a rich set of operators. C# operators can be classified into a number of related categories as below:

  1. Arithmetic operators
  2. Relational operators
  3. Logical operators
  4. Assignment operators
  5. Conditional operators
  6. Bitwise operators
  7. Miscellaneous operators
  1. Arithmetic Operator

Arithmetic operators are used to perform arithmetic operations such as addition, subtraction, multiplication, division, etc. C# provides all the basic arithmetic operators. The operators +, -, and / all work the same way as they do in other languages.

OperatorDescriptionExample
+Adds two operandsA + B = 30
Subtracts second operand from the firstA – B = -10
*Multiplies both operandsA * B = 200
/Divides numerator by de-numeratorB / A = 2
%Modulus Operator and remainder of after an integer divisionB % A = 0
++Increment operator increases integer value by oneA++ = 11
Decrement operator decreases integer value by oneA– = 9

Code:

        using System;

namespace Operators

{

    class Program

    {

        static void Main(string[] args)

        {

            int a = 21;

            int b = 10;

            int c;

            c = a + b;

            Console.WriteLine(“Line 1 – Value of c is {0}”, c);

            c = a – b;

            Console.WriteLine(“Line 2 – Value of c is {0}”, c);

            c = a * b;

            Console.WriteLine(“Line 3 – Value of c is {0}”, c);

            c = a / b;

            Console.WriteLine(“Line 4 – Value of c is {0}”, c);

            c = a % b;

            Console.WriteLine(“Line 5 – Value of c is {0}”, c);

            c = a++;

            Console.WriteLine(“Line 6 – Value of c is {0}”, c);

            c = a–;

            Console.WriteLine(“Line 7 – Value of c is {0}”, c);

            Console.ReadLine();

        }

    }

}

                         Output:

Line 1 – Value of c is 31

Line 2 – Value of c is 11

Line 3 – Value of c is 210

Line 4 – Value of c is 2

Line 5 – Value of c is 1

Line 6 – Value of c is 21

Line 7 – Value of c is 22

  • Relation Operator

Relational operators are used to check the relationship between two operands. If the relationship is true the result will be true, otherwise it will result in false.

Relational operators are used in decision making and loops.

OperatorDescriptionExample
==Two operands are equal or not, if yes then condition becomes true.(A == B) is not true.
!=Two operands are equal or not, if values are not equal then condition becomes true.(A != B) is true.
Left operand is greater than the value of right operand, if yes then condition becomes true.(A > B) is not true.
Left operand is less than the value of right operand, if yes then condition becomes true.(A < B) is true.
>=Left operand is greater than or equal to the value of right operand, if yes then condition becomes true.(A >= B) is not true.
<=Left operand is less than or equal to the value of right operand, if yes then condition becomes true.(A <= B) is true.

Code:

                                                using System;

class Program

{

    static void Main(string[] args)

    {

        int a = 21;

        int b = 10;

        if (a == b)

        {

            Console.WriteLine(“Line 1 – a is equal to b”);

        }

        else

        {

            Console.WriteLine(“Line 1 – a is not equal to b”);

        }

        if (a < b)

        {

            Console.WriteLine(“Line 2 – a is less than b”);

        }

        else

        {

            Console.WriteLine(“Line 2 – a is not less than b”);

        }

        if (a > b)

        {

            Console.WriteLine(“Line 3 – a is greater than b”);

        }

        else

        {

            Console.WriteLine(“Line 3 – a is not greater than b”);

        }

        /* Lets change value of a and b */

        a = 5;

        b = 20;

        if (a <= b)

        {

            Console.WriteLine(“Line 4 – a is either less than or equal to  b”);

        }

        if (b >= a)

        {

            Console.WriteLine(“Line 5-b is either greater than or equal to b”);

        }

    }

}

                                Output:

                                                Line 1 – a is not equal to b

Line 2 – a is not less than b

Line 3 – a is greater than b

Line 4 – a is either less than or equal to b

Line 5 – b is either greater than or equal to b

  • Logical Operator

Logical operators are used to perform logical operation such as and, or. Logical operators operates on boolean expressions (true and false) and returns boolean values. Logical operators are used in decision making and loops.

OperatorDescriptionExample
&&If both the operands are non-zero then condition becomes true.(A && B) is false.
||If any of the two operands is non zero then condition becomes true.(A || B) is true.
!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.

       Code:

                using System;

namespace OperatorsAppl {

   class Program {

      static void Main(string[] args) {

         bool a = true;

         bool b = true;

         if (a && b) {

            Console.WriteLine(“Line 1 – Condition is true”);

         }

         if (a || b) {

            Console.WriteLine(“Line 2 – Condition is true”);

         }

         /* lets change the value of  a and b */

         a = false;

         b = true;

         if (a && b) {

            Console.WriteLine(“Line 3 – Condition is true”);

         } else {

            Console.WriteLine(“Line 3 – Condition is not true”);

         }

         if (!(a && b)) {

            Console.WriteLine(“Line 4 – Condition is true”);

         }

         Console.ReadLine();

      }

   }

}

                Output:

                                Line 1 – Condition is true

Line 2 – Condition is true

Line 3 – Condition is not true

Line 4 – Condition is true

  • Assignment Operator

Assignment operators are used to assign the value of an expression to a variable. We have seen the usual assignment operator, ‘=’.

OperatorDescriptionExample
=Assigns values from right side operands to left side operandC = A + B assigns value of A + B into C
+=It adds right operand to the left operand and assign the result to left operandC += A is equivalent to C = C + A
-=It subtracts right operand from the left operand and assign the result to left operandC -= A is equivalent to C = C – A
*=It multiplies right operand with the left operand and assign the result to left operandC *= A is equivalent to C = C * A
/=It divides left operand with the right operand and assign the result to left operandC /= A is equivalent to C = C / A
%=It takes modulus using two operands and assign the result to left operandC %= A is equivalent to C = C % A
<<=Left shift AND assignment operatorC <<= 2 is same as C = C << 2
>>=Right shift AND assignment operatorC >>= 2 is same as C = C >> 2
&=Bitwise AND assignment operatorC &= 2 is same as C = C & 2
^=bitwise exclusive OR and assignment operatorC ^= 2 is same as C = C ^ 2
|=bitwise inclusive OR and assignment operatorC |= 2 is same as C = C | 2

Code:

        using System;

namespace OperatorsAppl

{

    class Program

    {

        static void Main(string[] args)

        {

            int a = 21;

            int c;

            c = a;

            Console.WriteLine(“Line 1 – =  Value of c = {0}”, c);

            c += a;

            Console.WriteLine(“Line 2 – += Value of c = {0}”, c);

            c -= a;

            Console.WriteLine(“Line 3 – -=  Value of c = {0}”, c);

            c *= a;

            Console.WriteLine(“Line 4 – *=  Value of c = {0}”, c);

            c /= a;

            Console.WriteLine(“Line 5 – /=  Value of c = {0}”, c);

            c = 200;

            c %= a;

            Console.WriteLine(“Line 6 – %=  Value of c = {0}”, c);

            c <<= 2;

            Console.WriteLine(“Line 7 – <<=  Value of c = {0}”, c);

            c >>= 2;

            Console.WriteLine(“Line 8 – >>=  Value of c = {0}”, c);

            c &= 2;

            Console.WriteLine(“Line 9 – &=  Value of c = {0}”, c);

            c ^= 2;

            Console.WriteLine(“Line 10 – ^=  Value of c = {0}”, c);

            c |= 2;

            Console.WriteLine(“Line 11 – |=  Value of c = {0}”, c);

            Console.ReadLine();

        }

    }

}

                Output:

                                Line 1 – = Value of c = 21

Line 2 – += Value of c = 42

Line 3 – -= Value of c = 21

Line 4 – *= Value of c = 441

Line 5 – /= Value of c = 21

Line 6 – %= Value of c = 11

Line 7 – <<= Value of c = 44

Line 8 – >>= Value of c = 11

Line 9 – &= Value of c = 2

Line 10 – ^= Value of c = 0

Line 11 – |= Value of c = 2

  • Conditional Operator

Ternary operator is a Conditional operator in C#. It takes three arguments and evaluates a Boolean expression.

b = (a == 1) ? 20 : 30;

Above, if the first operand evaluates to true (1), the second operand is evaluated. If the first operand evaluates to false (0), the third operand is evaluated.

Code:

using System;

namespace DEMO {

   class Program {

      static void Main(string[] args) {

         int a, b;

         a = 10;

         b = (a == 1) ? 20 : 30;

         Console.WriteLine(“Value of b is {0}”, b);

         b = (a == 10) ? 20 : 30;

         Console.WriteLine(“Value of b is {0}”, b);

         Console.ReadLine();

      }

   }

}

Output:

Value of b is 30

Value of b is 20

  • Bitwise Operator

Bitwise and bit shift operators are used to perform bit manipulation operations.

OperatorDescriptionExample
&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

Code:

        using System;

namespace OperatorsAppl

{

    class Program

    {

        static void Main(string[] args)

        {

            int a = 60;            /* 60 = 0011 1100 */

            int b = 13;            /* 13 = 0000 1101 */

            int c = 0;

            c = a & b;             /* 12 = 0000 1100 */

            Console.WriteLine(“Line 1 – Value of c is {0}”, c);

            c = a | b;             /* 61 = 0011 1101 */

            Console.WriteLine(“Line 2 – Value of c is {0}”, c);

            c = a ^ b;             /* 49 = 0011 0001 */

            Console.WriteLine(“Line 3 – Value of c is {0}”, c);

            c = ~a;                /*-61 = 1100 0011 */

            Console.WriteLine(“Line 4 – Value of c is {0}”, c);

            c = a << 2;      /* 240 = 1111 0000 */

            Console.WriteLine(“Line 5 – Value of c is {0}”, c);

            c = a >> 2;      /* 15 = 0000 1111 */

            Console.WriteLine(“Line 6 – Value of c is {0}”, c);

            Console.ReadLine();

        }

    }

}

                Output:

                                Line 1 – Value of c is 12

Line 2 – Value of c is 61

Line 3 – Value of c is 49

Line 4 – Value of c is -61

Line 5 – Value of c is 240

Line 6 – Value of c is 15

  • Miscellaneous Operator
OperatorDescriptionExample
sizeof()Returns the size of a data type.sizeof(int), returns 4.
typeof()Returns the type of a class.typeof(StreamReader);
&Returns the address of an variable.&a; returns actual address of the variable.
*Pointer to a variable.*a; creates pointer named ‘a’ to a variable.
? :Conditional ExpressionIf Condition is true ? Then value X : Otherwise value Y
isDetermines whether an object is of a certain type.If( Ford is Car) // checks if Ford is an object of the Car class.
asCast without raising an exception if the cast fails.Object obj = new StringReader(“Hello”); StringReader r = obj as StringReader;

Example:

        using System;

namespace OperatorsAppl {

   class Program {

      static void Main(string[] args) {

         /* example of sizeof operator */

         Console.WriteLine(“The size of int is {0}”, sizeof(int));

         Console.WriteLine(“The size of short is {0}”, sizeof(short));

         Console.WriteLine(“The size of double is {0}”, sizeof(double));

         /* example of ternary operator */

         int a, b;

         a = 10;

         b = (a == 1) ? 20 : 30;

         Console.WriteLine(“Value of b is {0}”, b);

         b = (a == 10) ? 20 : 30;

         Console.WriteLine(“Value of b is {0}”, b);

         Console.ReadLine();

      }

   }

}

                Output:

                                The size of int is 4

The size of short is 2

The size of double is 8

Value of b is 30

Value of b is 20

Also, Read

  1. Unit: 8 Inheritance
  2. Unit: 9 Packages and Interface
  3. Unit: 10 Exception Handling
  4. Unit-11 Multithreaded Programming
  5. Unit:12 Enumerations, autoboxing, and annotations
  6. Unit:13 String handling
Sharing Is Caring:

Desktop and Android Developer

1 thought on “Chapter: 1 Introduction to C#.NET”

Leave a Comment

Slide to prove you're not a bot/spammer *