Skip to content

Instantly share code, notes, and snippets.

@SLIB53
Last active August 29, 2015 14:27
Show Gist options
  • Save SLIB53/f73420ff3fa480368548 to your computer and use it in GitHub Desktop.
Save SLIB53/f73420ff3fa480368548 to your computer and use it in GitHub Desktop.
A sample C# script used to explain Idiomatic vs Non-idiomatic styled code.
#define NON_IDIOMATIC
#undef NON_IDIOMATIC //comment this line out to compile idiomatic code.
#if NON_IDIOMATIC
using System;
#else
using static System.Console;
#endif
namespace NonIdiomatic_VS_Idiomatic_CSharp
{
#if NON_IDIOMATIC
public class Cat
{
private String _name;
public Cat(String name)
{
_name = name;
}
public String GetName()
{
return _name;
}
}
internal class Program
{
private static void Main(string[] args)
{
Cat akil = new Cat("akil");
String catName = akil.GetName();
Console.WriteLine(catName);
//// Wait...
Console.ReadKey();
}
}
#else
public class Cat
{
public string Name { get; }
public Cat(string name)
{
Name = name;
}
}
internal class Program
{
private static void Main(string[] args)
{
var akil = new Cat("akil");
string catName = akil.Name;
/* Here's another way:
Cat akil;
akil = new Cat(nameof(akil));
* This special way helps enforce that the cat
* shares it's runtime name with it's variable name.
*/
Write(catName);
//// Wait...
ReadKey();
}
}
#endif
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment