Saturday, January 21, 2012

Saturday 1-21-12

namespace GeneralCoding
{
class Program
{
static void Main(string[] args)
{
DeferType();
ConditionalOperator();
}

class Person
{
public int Id { get; set; }
public string Name { get; set; }
public string Address {get; set;}
}

class Company
{
public int Id {get; set;}
public string Name { get; set; }
public bool isBig {get; set;}
}

static void DeferType()
{
//declare three types that have nothing to do with each other
//but all have an Id and name property

Person p = new Person() { Id = 1, Name = "Ben", Address="Redmond, WA"};
Company c = new Company() { Id = 1313, Name="Microsoft", isBig = true};
var v = new {Id = 13, Name="Widget", Silly = true};

PrintInfo(p);
PrintInfo(c);
PrintInfo(v);

}

static void PrintInfo(dynamic data)
{
//will print anythign that has an Id and Name property
Console.WriteLine("ID: {0}, Name: {1}", data.Id, data.Name);
}

//declare an array of objects
static void ArrayDeclaration()
{
//these are all equivalent
int[] array1 = new int[4];
array1[0] = 13; array1[1] = 15; array1[2] = 15; array1[3] = 16;

int[] array2 = new int[4] {13, 14, 15, 16};

int[] array3 = new int[] {13, 14, 15, 16};

int[] array4 = {13, 14, 15, 16};
}

static void ConditionalOperator()
{
bool condition = true;

int x = condition ? 13 : 14;
Console.WriteLine("x is {0}", x);

//you can also embed the condition in other statements
Console.WriteLine("Condition is {0}", condition ? "TRUE" : "FALSE");
}
}
}


class Program
{
static void Main(string[] args)
{
for (int i = 0; i < 100; ++i)
{
if (i.IsPrime())
{
Console.WriteLine(i);
}
}
Console.ReadKey();
}
}

static class IntMethods
{
//extension methods must be static
//the this keyword tells C# that this is an extension method
public static bool IsPrime(this int number)
{
//check for evenness
if (number % 2 == 0)
{
if (number == 2)
return true;
return false;
}

//don't need to check past the square
int max = (int)Math.Sqrt(number);
for (int i= 3; i <= max; i += 2)
{
if ((number % i) == 0)
{
return false;
}
}
return true;
}
}

No comments:

Post a Comment