C# Misc Stuff π·πΌββοΈπ·πΌββοΈ
Main
This is C# so Main
is captialised. Also, it can be set to return void
instead of int
public class MyClass
{
public static int Main( )
{
}
}
Class Members
Default access modifier is private (but itβs best to declare this explicitly)
- public
- private
- protected - accessible by any class derived from this class
- internal - accessible by any method in this classβs assembly
- protected internal - same as protected OR internal
Default values
- numeric => 0
- bool => false
- char => 0
- enum => 0
- ref => null
Method Arguments
Pass by value (can be made to pass by reference with the ref keyword)
Default values for arguments
Public void myMethod(int x = 42) // setting a default value
{ β¦
Pass by reference
// method signature
public void GetTime(ref int h, ref int min, ref sec)
{
// code
}
//method call
t.GetTime(ref hour, ref min, ref sec);
NOTE: Cannot pass an uninitialised variable as a reference argument
Constructors
public class MyClass
{
public MyClass(int number)
{
β¦
}
}
- just like in Java
- can be overloaded
- can be marked as private
Copy Constructors
Creates a new object by copying an existing object, eg.
public MyClass(MyClass myClass)
{
β¦
this.number = myClass.number
...
}
Also check out the ICloneable interface in .NET
Static Methods
Button.StaticMethod();
cannot access via an instance of Button.
Static Constructors
Creates a new object by copying an existing object, eg.
Static Time()
{
Name = βTimeβ;
}
- run before any object is instantiated
- no access modifiers on static constructors
Destroying Objects
An object's destructor is called when object is garbage collected - never call this yourself! - leave it to the garbage collector.
~MyClass()
{
// my code
}
This get translated to:
protected override void Finalize()
{
try
{
// my code
}
finally
{
base.Finalize();
}
}
Dispose
Used to dispose of precious resources as quickly as possible. (e.g. file handles)
using System;
class Testing : IDisposable // IDisposable requires implements to define public void Dispose()
{
bool is_disposed = false;
protected virtual void Dispose(bool disposing)
{
if(!is_disposed) // only dispose once!
{
if(disposing)
{
Console.WriteLine("Not in destructor, OK to reference other objects");
}
// perform clean up for this object
Console.WriteLine("Disposing...");
}
this.is_disposed = true;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this); // stops the GC from calling this object's destructor
}
~Testing()
{
Dispose(false);
Console.WriteLine("In destructor");
}
}
Disposing of resources with 'using'
using System;
class Test
{
public static void Main()
{
// METHOD 1.
using(Font theFont = new Font("Arial", 10.0f)) // initialising
{
// use the font here
} // compiler will now call Dispose() on the Font at this point
// METHOD 2.
Font nextFont = new Font("Courier",12.0f);
using(nextFont)
{
// do some in Courier 12
} // compile now calls Dispose() on nextFont
}
}