Click here to Skip to main content
6,292,426 members and growing! (10,303 online)
Email Password   helpLost your password?
Languages » C# » General     Intermediate License: The Code Project Open License (CPOL)

C# Language Infrequent Methods, Operators and Techniques

By vivekgaur

Here I provide a basic overview of some things which are included in .NET 2.0/1.1 but only few developers are using them. I am not saying that nobody knows about these functions, Operators or facilities but only few developers are using these based on their requirements.
C# 2.0, Windows, .NET 1.1, .NET 2.0VS.NET2003, VS2005, Dev
Posted:4 May 2007
Views:15,106
Bookmarked:23 times
Announcements
Loading...
 
Search    
Advanced Search
printPrint   Broken Article?Report       add Share
  Discuss Discuss   Recommend Article Email
21 votes for this article.
Popularity: 5.21 Rating: 3.94 out of 5

1
2 votes, 9.5%
2
2 votes, 9.5%
3
11 votes, 52.4%
4
6 votes, 28.6%
5

Introduction

Since the last two years, I have been working in various .NET technologies as a software developer. I have worked on both .Net 1.1 & .NET 2.0. Recently, we migrated our projects from .NET 1.1 to 2.0. There are lots of new facilities provided by Visual Studio 2005. Here I provide a basic overview of some things which are included in .NET 2.0/1.1 but only few developers are using them. I am not saying that nobody knows about these functions, Operators or facilities but only few developers are using these according to their requirement.

The Checked and Unchecked Operators

Consider the following code:

byte b = 255; 
b++; 
Console.WriteLine (b.ToString ());

The byte data type can only hold values in the range zero to 255, so incrementing the value of b causes an overflow. How the CLR handles this depends on a number of issues, including compiler options, so whenever there's a risk of an unintentional overflow, you need some way of making sure that you get the result you want.

To do this, C# provides the checked and unchecked operators. If you mark a block of code as checked, the CLR will enforce overflow checking, and throw an OverflowException if an overflow occurs. Let's change the code to include the checked operator:

byte b = 255; 
checked 
{ 
b++; 
} 

Console.WriteLine (b.ToString ());

When you try to run this code, you will get an error message like this:

Unhandled Exception: System.OverflowException: Arithmetic operation resulted in an
Overflow.
   at Demo.DemoCSharp.OverflowTest.Main(String[] args)

If you want to suppress the overflow checking, you can mark the code as unchecked as shown below:

byte b = 255;
unchecked
{ 
b++;
} 

Console.WriteLine (b.ToString ()); 

In this case, you will lose the data but no exception will arise.

The Nullable Types and Operators

In C# 2005, due to generics, it is now possible to create nullable value types using System.Nullable<T>.

To create a nullable type of int, we can use this syntax:

System.Nullable<int> x = new System.Nullable<int>;

There is a new type modifier that you can use to create type as nullable in following way:

int? a =null;
int? b= a + 4;
int?c = a +5; 

The Null Coalescing Operator

The null coalescing operator (??) provides a shorthand mechanism to handle the possibility of null values when working with nullable & reference types. The operator is placed between two operands - the first operand must be a nullable type or reference type and the second operand must be of the same type as the first or of the type that is implicitly convertible to the type of the first operand. It evaluate as: if the first operand is not null, then the overall expression has the value of the first operand, however if the first operand is null, the overall expression has the value of the second operand. For example:

int? a =null; 
int b; 
b=a??10; // b has value 10 
a=5; 
b=a??10; //b has value 5 

The As Operator

This operator is used to perform explicit type conversion of reference types. If the type being converted is compatible with specified type, conversion is performed successfully otherwise this operator returns null value.

object o1 ="my string"; 
object o2 =25; 
string str1= o1 as string; //str1="my string" 
string str2 = o2 as string; //str2=null 

Preprocessor #warning and #error

These will respectively cause a warning or an error to be raised when the compiler encounters them.

For example:

#if DEBUG && RELEASE 
#error "You have defined DEBUG & RELEASE simultaneously." 
#end if 
#warning "Don't forget to remove this line before setup." 
Console.WriteLine(" Some message"); 

The ReferenceEquals() Method

ReferenceEquals() is a static method that tests whether two references refer to the same instance of a class; specifically whether the two references contain the same address in memory. As a static method, it is not possible to override, so the System.Object implementation is what you always have. ReferenceEquals() will always return true if supplied with two references that refer to the same object instance, and false otherwise. It does, however, consider null to be equal to null:

SomeClass x, y;
x = new SomeClass(); 
y = new SomeClass(); 
bool B1 = ReferenceEquals(null, null); // returns true 
bool B2 = ReferenceEquals(null,x);     // returns false 
bool B3 = ReferenceEquals(x, y);       // returns false because x and y 
                                       // point to different objects 

Another point is that ReferenceEquals() always returns false when applied to value types, because to call this method, the value types will need to be boxed into objects. Even if you write...

bool b = ReferenceEquals(v,v);         // v is a variable of some value type 

... you will still get the answer of false because v will be boxed separately when converting each parameter, which means you get different references. Calling ReferenceEquals() to compare value types doesn't really make much sense.

History

  • 4th May, 2007: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

vivekgaur


Member
I am MCAD certified ,working with PureDev(www.puredev.in).PureDEV provides software development services and product engineering services.PureDEV brings all the benefits of offshore software development, global delivery model, highest levels of quality, best processes and best of the breed software professionals.
Occupation: Software Developer (Senior)
Company: PureDev Software Pvt. Ltd
Location: India India

Other popular C# articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 11 of 11 (Total in Forum: 11) (Refresh)FirstPrevNext
GeneralNot really obscure [modified] PinmemberAndrew Phillips5:17 9 May '07  
GeneralRe: Not really obscure Pinmembervivekgaur5:29 9 May '07  
GeneralGood article Pinmemberroman.wagner21:42 8 May '07  
General?? operator PinmemberSebrell2:05 8 May '07  
GeneralNever knew about the ?? operator Pinmemberreinux13:00 4 May '07  
GeneralRe: Never knew about the ?? operator Pinmembervivekgaur3:58 6 May '07  
GeneralExcellent Pinmembermerlin9818:37 4 May '07  
GeneralMisleading PinmvpJ4amieC7:17 4 May '07  
GeneralRe: Misleading Pinmembervivekgaur4:05 6 May '07  
GeneralExcellent!! Pinmemberlogan13376:24 4 May '07  
GeneralRe: Excellent!! Pinmembervivekgaur3:59 6 May '07  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 4 May 2007
Editor: Deeksha Shenoy
Copyright 2007 by vivekgaur
Everything else Copyright © CodeProject, 1999-2009
Web20 | Advertise on the Code Project