Last active
August 29, 2015 14:27
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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