C# FAQ: Are references the same in Cplusplus and CSharp
Microsoft .NET Framework, ASP.NET, Visual C# (CSharp, C Sharp, C-Sharp) Developer Training, Visual Studio
| CSharp-Online.NET:FAQs |
| edit |
[edit]
Are references the same in C++ and C#?
There is one significant difference between C++ and C# references: C# references can be null. Therefore, a C# reference may not point to a valid object. A C# reference is a bit like a C++ pointer in this regard.
An attempt to reference a null reference will cause a NullReferenceException to be thrown. For example, a method such as the following:
void displayStringLength (string displayString) { Console.WriteLine ("String length is: {0}.", displayString.Length); }
The preceding method will throw a NullReferenceException if called with a null reference as follows:
displayStringLength (null);
In many situations, a NullReferenceException may be a valid result. However, it would be better to rewrite the preceding example to catch null references like this:
void displayStringLength (string displayString) { if( displayString == null ) { Console.WriteLine ("String reference is null."); } else { Console.WriteLine ("String length is: {0}.", displayString.Length); } }