|
using System;
using System.Collections.Generic;
/* contact:
* abhijit.gadkari@gmail.com
*
* */
namespace ExtensionMethods
{
interface IPerson
{
int age { get; set; }
String name { get; set; }
}
class Person : IPerson
{
private int _age;
private string _name;
#region IPerson Members
public int age
{
get
{
return _age;
}
set
{
if (value > 0)
{
_age = value;
}
}
}
public string name
{
get
{
return _name;
}
set
{
if (!string.IsNullOrEmpty(value))
{
_name = value;
}
else
{
_name = "Unknown";
}
}
}
#endregion
}
static class ExtendIPerson
{
public static bool CanDrive(this IPerson testPerson, bool isDriver)
{
return isDriver;
}
}
public static class ExtensionMethods
{
public static bool IsGreaterThanZero(this int Number)
{
return Number > 0 ? true : false;
}
}
public class City
{
private string _name;
private string _state;
public City(string name, string state)
{
this._name = name;
this._state = state;
}
public string Name
{
get
{
return _name;
}
}
public string State
{
get
{
return _state;
}
}
}
public static class ExtendCity
{
public static bool IsCityinCalifornia(this City c)
{
return c.State == "CA" ? true : false;
}
}
class Program
{
static bool StaticIsGreaterThanZero(int Number)
{
return Number > 0 ? true : false;
}
static void Main(string[] args)
{
#region Simple IF logic
int NumOne = 10;
if (NumOne > 0)
Console.WriteLine("Number : {0} is greater than 0", NumOne);
#endregion
#region decouple IF logic into a seperate static method
if (StaticIsGreaterThanZero(NumOne))
{
Console.WriteLine("Number : {0} is greater than 0", NumOne);
}
#endregion
#region Extension method implementation
if (NumOne.IsGreaterThanZero())
{
Console.WriteLine("Number : {0} is greater than 0", NumOne);
}
#endregion
#region Extending the custom type
City c = new City("Santa Ana", "CA");
City c1 = new City("Bloomington", "IN");
List<City> cities = new List<City>();
cities.Add(c);
cities.Add(c1);
foreach (City _city in cities)
{
//IsCityinCalifornia() is an extension method
if (_city.IsCityinCalifornia())
{
Console.WriteLine("City Name : {0} and City State : {1}", _city.Name, _city.State);
}
}
#endregion
#region Mixin Implementation
IPerson ip = new Person();
ip.name = "ABC";
ip.age = 21;
if (ip.CanDrive(true))
{
Console.WriteLine(ip.name + " can drive");
}
#endregion
Console.ReadLine();
}
}
}
|
By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.
If a file you wish to view isn't highlighted, and is a text file (not binary), please
let us know and we'll add colourisation support for it.