You are on page 1of 22

By,

Nagabhushana. B
M.Tech CNE 1st Sem

The Advanced Keywords of C#


checked / unchecked
unsafe / stackalloc / fixed /

volatile / sizeof
lock

checked keyword
Each numerical data type has a fixed upper and lower

limit. (MaxValue/MinValue)
both overflow and underflow conditions result in a

System.OverflowException type.
There is no System.UnderflowException type in the

base class libraries

namespace Checkedkeyword { class TheChecker { static void Main(string[] args) { // Overflow the max value of a System.Byte. Console.WriteLine("Max value of byte is {0}.", byte.MaxValue); Console.WriteLine("Min value of byte is {0}.", byte.MinValue); byte b1 = 100; byte b2 = 250; byte b3 = (byte)(b1 + b2); // b3 should hold the value 350, however... Console.WriteLine("b3 = {0}", b3); } } }

b3 contains the value 94 (rather than the expected 350) Reason is, a System.Byte can only hold a value between 0 and

255.(grand total of 256 slots)

b3 now contains the overflow value (350 256 = 94) To handle overflow or underflow conditions 2 possibilities. First,

leverage your wits and Second, programming skills to handle all overflow conditions manually.

// Store sum in an integer to prevent overflow. byte b1 = 100; byte b2 = 250; int answer = b1 + b2;

C# provides the "checked" keyword

static void Main(string[] args) { // Overflow the max value of a System.Byte. Console.WriteLine("Max value of byte is {0}.", byte.MaxValue); byte b1 = 100; byte b2 = 250; try { byte b3 = checked((byte)(b1 + b2)); Console.WriteLine("b3 = {0}", b3); } catch(OverflowException e) { Console.WriteLine(e.Message); } }

Overflow checking to occur over a block of code.

For ex: try { checked { byte b3 = (byte)(b1 + b2); byte b4, b5 = 100, b6 = 200; b4 = (byte)(b5 + b6); Console.WriteLine("b3 = {0}", b3); } } catch(OverflowException e) { Console.WriteLine(e.Message); }

unchecked keyword
C# language provides the "unchecked" keyword to disable the throwing of System.OverflowException on a case-by-case basis. The use of this keyword is identical to the "checked" keyword in that you can specify a single statement or a block of statements.

For example: // Assuming +checked is enabled, // this block will not trigger // a runtime exception. unchecked { byte b3 = (byte)(b1 + b2); Console.WriteLine("b3 = {0}", b3); }
the default behavior of the .NET runtime is to ignore arithmetic overflow.

C# provides some of the Pointer-centric C# operators.


C# Pointer- Meaning in life Centric Operator * Used to create a pointer variable, a variable that represents a direct location in memory. Like C(++), this same operator is used to represent pointer indirection. Used to obtain the address of a pointer. This operator is used to access fields of a type that is represented by a pointer variable (the unsafe version of the C# dot operator).

& ->

[]

The [] operator (in an unsafe context) allows you to index the slot pointed to by a pointer variable (recall the interplay between a pointer variable and the [] operator in C(++)!).

unsafe keyword
Working with pointers in C#, we must specifically declare a block of unsafe code using unsafe keyword.
unsafe { // Work with pointers here! }

Unsafe keyword is used to declare class, structure type members and parameters that

are unsafe. For ex, // This entire structure is "unsafe" and can // be used only in an unsafe context. public unsafe struct Node { }
unsafe public static void SomeUnsafeCode() { // Work with pointers here! }

Working with the * and & Operators


Once we have established an unsafe context, then we can free to build pointers to data types using * and & operators. For ex, int *pi, *pj; // No! This is incorrect under C#! int* pi, pj; // Yes! This is the way of C#.

unsafe { int myInt; // Define an int pointer, and // assign it the address of myInt. int* ptrToMyInt = &myInt; // Assign value of myInt using pointer indirection. *ptrToMyInt = 123; // Print some stats. Console.WriteLine("Value of myInt {0}", myInt); Console.WriteLine("Address of myInt {0:X}", (int)ptrToMyInt); }

stackalloc keyword
In unsafe context we may need to declare a local

variable that allocates memory directly from the stack. for example unsafe static void UnsafeStackAlloc() { char* p = stackalloc char[256]; for (int k = 0; k < 256; k++) p[k] = (char)k; }

fixed keyword
of statement.

The fixed statement prevents the garbage collector from relocating a movable variable. The fixed statement is only permitted in an unsafe context. The fixed statement sets a pointer to a managed type and pins that variable during execution Without fixed pointer to managed variables would be of little use, since garbage collection

could reallocate the variables.

unsafe public static void UseAndPinPoint() { PointRef pt = new PointRef (); pt.x = 5; pt.y = 6; // pin pt in place so it will not // be moved or GC-ed. fixed (int* p = &pt.x) { // Use int* variable here! } // pt is now unpinned, and ready to be GC-ed. Console.WriteLine ("Point is: {0}", pt); }

volatile keyword
when we define a volatile variable, we are performing the converse

operation of pinning a type in memory, in that you are telling the runtime that it is completely fine to allow an outside agent (such as the operating system, the hardware, or a concurrently executing thread) to modify the item in question at any time.

Declaring volatile variable,

volatile int moveMeAnytime;


The volatile keyword may be used to define a type field that is

accessed by multiple threads without using the lock stmt. up-to-date value written by another thread.

Using the volatile modifier ensures that one thread retrieves the most

sizeof keyword
The final advanced C# keyword to consider is "sizeof".
Like C(++), the "sizeof" keyword is used to obtain the size

in bytes for a value type (never reference types), and may only be applied from within an unsafe context.
For ex, Console.WriteLine("The size of int is {0}.", sizeof(int)); Console.WriteLine("The size of long is {0}.", sizeof(long));

A Catelog of C# Keywords

Building custom Indexer


Indexer - the process of accessing discrete items held within a

standard array using the index (aka bracket) operator.


// Declare an array of integers. int[] myInts = { 10, 9, 100, 432, 9874}; // Use the [] operator to access each element. for(int j = 0; j < myInts.Length; j++) Console.WriteLine("Index {0} = {1} ", j, myInts[j]);

Indexers allow instances of a class or struct to be indexed just

like arrays.

namespace Indexers { class ParentClass { private string[] range = new string[5]; public string this[int indexrange] { get { return range[indexrange]; } set { range[indexrange] = value; } } }

class childclass { public static void Main() { ParentClass obj = new ParentClass(); /* The Above Class ParentClass create one object name is obj */ obj[0] = "ONE"; obj[1] = "TWO"; obj[2] = "THREE"; obj[3] = "FOUR "; obj[4] = "FIVE"; Console.WriteLine("WELCOME TO C# CORNER HOME PAGE\n"); Console.WriteLine("{0}\n,{1}\n,{2}\n,{3}\n,{4}\n", obj[0], obj[1], obj[2], obj[3], obj[4]); Console.WriteLine("\n"); Console.ReadLine(); } } } Beyond the use of the "this" keyword, the indexer looks just like any other C# property declaration. Do be aware that indexers do not provide any array-like functionality beyond the use of the subscript operator.

Thank you

You might also like