C# – Code examples



C# – Code examples

0 0


wwwind.github.io

My presentation for show-and-tell, 2015

On Github wwwind / wwwind.github.io

C#

Show-and-tell presentation

Created by Elena Zhelezina

Language popularity index

Resources

Code examples

Numerical types

decimal d = 10.1M;

double dip = double.InfinityPositive;
double din = double.InfinityNegative;
double nan = double.NaN;

string str = double.ToString();

Short-circuit

return (!windy && (rainy || sunny));
return (!windy & (rainy | sunny));

Value-type vs Reference-type

Boxing/unboxing concept for a unified type system
int x = 9;
object obj = x; // box the int

int y = (int)obj; // unbox the int

// copied
int i = 3;
object boxed = i;
i = 5;
Console.WriteLine(boxed); //3

Virtual function members

public class Asset
{
public string Name;
public virtual decimal Liability { get {return 0;}}
public sealed void getData {...}
}

// can inherit just one class
public class House: Asset
{
public decimal Morgage;
public override decimal Liability { get {return Morgage;}}
}

Partial classes

Partial types allow a type detinition to be split:
// PaymentFormGen.cs - auto-generated
partial class PaymentForm {..}

// PaymentForm.cs - hand-generated
partial class PaymentForm {..}

Classes vs Interfaces

public interface IEnumerator
{
bool MoveNext();
object Current {get;}
void Reset();
}
internal class Countdown: IEnumerator
{
int count = 11;
public bool MoveNext() {return count-- > 0;}
public object Current { get {return count;}}
public void Reset() { throw new NotSupportedException();}
}

Generics

class GenericClass<T, U> where T: SomeClass, SomeInterface
                         where U : new()
						 {...}

covariance

Stack<Bear> bears = new Stack<Bear>();
Stack<Animal> animals = bears; // Compile-time error

contravariance

public interface IPushable<in T> { void Push (T obj); }

IPushable<Animal> animals = new Stack<Animal>();
IPushable<Bear> bears = animals;
bears.Push(new Bear());

Demonstration

Examples are available on GitHub here