Last active
February 17, 2020 18:25
-
-
Save bellons91/6005ebf8c5c42e036cf98b2bfe40a903 to your computer and use it in GitHub Desktop.
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
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
namespace Code4ItExamples.Extension_methods | |
{ | |
public static class ExtensionMethodExamples | |
{ | |
public static void Do() | |
{ | |
var person = new Person() { Name = "Davide", Surname = "Bellone", BirthDate = new DateTime(1990, 1, 1) }; | |
var student = new Student() | |
{ | |
Name = "Elon", | |
Surname = "Musk", | |
BirthDate = new DateTime(1971, 6, 28), | |
StudentId = 123 | |
}; | |
Console.WriteLine(student.GetFullNameWithBirthDate()); | |
Console.WriteLine(student.GetFullStudentInfo()); | |
Console.WriteLine(student.GetInitials()); | |
Console.ReadKey(); | |
List<int> myList = new List<int>() { 2, 4, 82, 6, 223, 5, 7, 342, 234, 1 }; | |
Console.WriteLine(myList.GetRandom()); | |
Console.WriteLine(myList.GetRandom()); | |
Console.WriteLine(myList.GetRandom()); | |
Console.WriteLine(myList.GetRandom()); | |
} | |
} | |
public class Person | |
{ | |
public DateTime BirthDate { get; set; } | |
public string Name { get; set; } | |
public string Surname { get; set; } | |
public string GetFullName() => $"{Surname} {Name}"; | |
} | |
public class Student : Person | |
{ | |
public int StudentId { get; set; } | |
} | |
public static class MyExtensions | |
{ | |
public static string GetFullNameWithBirthDate(this Person person) | |
{ | |
return $"{person.BirthDate.ToString("yyy-MM-dd")} - {person.GetFullName()}"; | |
} | |
public static string GetFullStudentInfo(this Student student) | |
{ | |
return $"{student.GetFullName()} - ID: {student.StudentId}"; | |
} | |
public static string GetInitials(this Student student) | |
=> $"Student: {student.Surname.ToCharArray()[0]}.{student.Name.ToCharArray()[0]}."; | |
public static string GetInitials(this Person person) | |
=> $"Person: {person.Surname.ToCharArray()[0]}.{person.Name.ToCharArray()[0]}."; | |
public static T GetRandom<T>(this IEnumerable<T> source) | |
{ | |
if (source == null || source.Count() == 0) | |
throw new ArgumentException(nameof(source)); | |
Random rd = new Random(); | |
return source.ElementAt(rd.Next(0, source.Count())); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment