Monday, April 18, 2005

Types in C#

First time I saw the C# code in a magazine, I thought, Another new language, new syntax, new keywords…more confusion”. But now I don’t think so. C# is not completely different from other languages speaking of its syntax and approach. Moving further on, I learnt about the data types in C#.

C# supports two kinds of types: value types and reference types. No big deal. The name says it all. In case of values types, the variable stores the value directly and in case of reference types, it stores the reference to the variable (address). Other concepts like possibility of two variables referencing the same object are possible as in the case of C++.

A sample program to understand the types:

using System;
class ClassObj
{
public int num = 0;
}

class ClassTest
{
static void Main()
{
int x = 0;
int y = x;
y = 101;

ClassObj ref1 = new ClassObj();
ClassObj ref2 = ref1;
ref2.num = 999;

Console.WriteLine("Values: {0}, {1}", x, y);
Console.WriteLine("Refs: {0}, {1}", ref1.num, ref2.num);
}
}

C:\WINNT\Microsoft.NET\Framework\v1.0.3705>csc D:\cstypes.cs
Microsoft (R) Visual C# .NET Compiler version 7.00.9466
for Microsoft (R) .NET Framework version 1.0.3705
Copyright (C) Microsoft Corporation 2001. All rights reserved.

C:\WINNT\Microsoft.NET\Framework\v1.0.3705>cstypes
Values: 0, 101
Refs: 999, 999

An interesting thing that I’ve observed is the method used to print the formatted output in Console.WriteLine

Console.WriteLine takes a variable number of arguments. The first argument is a string, which may contain numbered placeholders like {0} and {1}. Each placeholder refers to a trailing argument with {0} referring to the second argument, {1} referring to the third argument, and so on. Before the output is sent to the console, each placeholder is replaced with the formatted value of its corresponding argument.

No comments: