Skip to content

Instantly share code, notes, and snippets.

@ericnel
Created May 17, 2010 14:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ericnel/403826 to your computer and use it in GitHub Desktop.
Save ericnel/403826 to your computer and use it in GitHub Desktop.
//#define runcalc
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Dynamic;
using Excel = Microsoft.Office.Interop.Excel;
namespace newfeatures
{
class Program
{
static void Main(string[] args)
{
var keepLooping = true;
int demo;
Console.WriteLine("===Choose a demo to run");
while (keepLooping)
{
#region noddy menu
Console.Write("\n> 1 Params, 2 Dynamic, 3 Excel, 4 Covariance, 5 Exit ?");
string s = Console.ReadLine();
Console.Clear();
var ignore = int.TryParse(s, out demo);
#endregion
switch (demo)
{
case 1: DemoOptionalParams();
break;
case 2: DemoDynamicObjects();
break;
case 3: DemoExcelWorkbook();
break;
case 4: DemoCovarianceAndContravariance();
break;
case 5:
keepLooping = false;
break;
}
}
}
private static void DemoOptionalParams()
{
Console.WriteLine("\n===Calling a method with optional parameters");
Console.WriteLine(@"Called with (1, 2, 'Henry', 4)");
MethodWithOptionalParams(1, 2, "Henry", 4);
Console.WriteLine("\nCalled with (10, 20)");
MethodWithOptionalParams(10, 20);
Console.WriteLine("\nCalled with (height: 100, width: 200)");
MethodWithOptionalParams(height: 100, width: 200);
Console.WriteLine("\nCalled with (width: 1000, height: 2000, depth: 3000)");
MethodWithOptionalParams(width: 1000, height: 2000, depth: 3000);
}
public static void MethodWithOptionalParams(int height, int width,
string name = "George", int depth = 0)
{
Console.WriteLine("h {0} w {1} n {2} d {3}", height, width, name, depth);
}
private static void DemoDynamicObjects()
{
#region dynamic type
Console.WriteLine("\n===Dynamic: Compiles even though method does not exist");
dynamic calc = new GetCalculator();
#if runcalc
int sum = calc.Add(10, 20);
#endif
#endregion
#region Expando
Console.WriteLine("\n===Dynamic: ExpandoObject gets a height prop at run time");
dynamic expando = new ExpandoObject();
expando.Height = 400;
Console.WriteLine("h {0}", expando.Height);
#endregion
#region Your own dynamic object
Console.WriteLine("\n===Dynamic: Calling an unimplemented property on a dynamic object");
dynamic firstDynamicObject = new FirstDynamicObject();
Console.WriteLine("Height = {0}", firstDynamicObject.Height);
firstDynamicObject.SomePropertyThatDoesntExist = 42;
Console.WriteLine("LastSetter = {0}", firstDynamicObject.LastSetter);
#endregion
}
private static void DemoExcelWorkbook()
{
// Say goodbye to 'missing'. Don't need this anymore or Type.Missing
object missing = System.Reflection.Missing.Value;
Console.WriteLine("\n===Dynamic: Create an Excel Workbook - but no need for a PIA, and uses optional etc");
int[] values = { 20, 19, 3, 42 };
var filePath = @"C:\Temp";
Excel.Application excelApp = null;
Excel.Workbook workbook;
Excel.Worksheet worksheet;
try
{
excelApp = new Excel.Application();
workbook = excelApp.Workbooks.Add();
worksheet = workbook.Sheets.Add() as Excel.Worksheet;
worksheet.Name = "Sample Worksheet";
for (int i = 1; i <= values.Length; i++)
{
worksheet.Cells[i, 1] = values[i - 1];
}
excelApp.DisplayAlerts = false;
string folderPath = Path.GetDirectoryName(filePath);
if (!Directory.Exists(folderPath))
{
Directory.CreateDirectory(folderPath);
}
workbook.SaveAs(filePath);
}
finally
{
worksheet = null;
workbook = null;
excelApp.Quit();
excelApp = null;
}
}
private static void DemoCovarianceAndContravariance()
{
var derivedList = new List<Derived>();
var item1 = new Derived {Identity = Guid.NewGuid(), BaseField = 1, DerivedField = 41};
var item2 = new Derived {Identity = item1.Identity, BaseField = 2, DerivedField = 42};
var item3 = new Derived {Identity = Guid.NewGuid(), BaseField = 3, DerivedField = 43 };
derivedList.Add(item1);
derivedList.Add(item2);
derivedList.Add(item1);
derivedList.Add(item3);
derivedList.Add(item3);
// Covariance
Console.WriteLine("\n===Calling method expecting Base but passing in Derived");
ProcessBases(derivedList);
// Contravariance
Console.WriteLine("\n===Deduping Derived using default comparer");
var dedupedDef = derivedList.Distinct<Derived>();
ProcessBases(dedupedDef);
Console.WriteLine("\n===Deduping Derived using Base Comparer. Expects a Derived Comparer");
var deduped = derivedList.Distinct<Derived>(new BaseComparer());
ProcessBases(deduped);
}
private static void ProcessBases(IEnumerable<Base> bases)
{
Console.WriteLine("\nProcessing list of Bases:");
foreach (Base item in bases)
{
Console.WriteLine("Id {0} Bf {1}", item.Identity, item.BaseField);
}
}
}
// Supporting classes
#region classes used by dynamic demos
public class GetCalculator
{
}
public class FirstDynamicObject : DynamicObject
{
private static string _yukkybutworks;
public static string LastSetter
{
get { return _yukkybutworks; }
}
public override bool TryGetMember(GetMemberBinder binder,
out object result)
{
if (binder.Name == "LastSetter")
result = _yukkybutworks;
else
result = "Member " + binder.Name + " is not yet implemented";
return true;
}
public override bool TrySetMember(SetMemberBinder binder, object value)
{
_yukkybutworks = value.ToString();
return true;
}
}
#endregion
#region covariance and contravariance classes
public class Base
{
public Guid Identity { get; set; }
public int BaseField { get; set; }
}
public class Derived : Base
{
public int DerivedField { get; set; }
}
public class BaseComparer : IEqualityComparer<Base>
{
public bool Equals(Base x, Base y)
{
if (object.ReferenceEquals(x, y)) return true;
if (object.ReferenceEquals(x, null)) return false;
if (object.ReferenceEquals(y, null)) return false;
return x.Identity == y.Identity;
}
public int GetHashCode(Base @base)
{
if (object.ReferenceEquals(@base, null)) return 0;
return @base.Identity == null ? 0 : @base.Identity.GetHashCode();
}
}
#endregion
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment