class Program
{
static void Main(string[] args)
{
string post = "This is supposed to be a very long blog post blah blah blah...";
var shortenedPost = post.Shorten(5);
Console.WriteLine(shortenedPost);
IEnumerable<int> numbers = new List<int>() { 1, 5, 3, 10, 2, 18 };
var max = numbers.Max();
Console.WriteLine(max);
Console.ReadLine();
}
}
public static class StringExtensions
{
public static string Shorten(this String str, int numberOfWords)
{
if (numberOfWords < 0)
throw new ArgumentOutOfRangeException("numberOfWords should be greater than or equal to 0.");
if (numberOfWords == 0)
return "";
var words = str.Split(' ');
if (words.Length <= numberOfWords)
return str;
return string.Join(" ", words.Take(numberOfWords)) + "...";
}
}
public static class MyClassExtension
{
// This is the method you are adding to a class "MyClass"
public static string GetValue(this MyClass myClass)
{
return value.toString();
}
}
// This is how you can use it in other parts of your code
MyClass myClass = new MyClass();
string s = myClass.GetValue();
public static void ExtensionMethodName(this ClassToExtend o)
{
//Do stuff
}
// list of useful extension methods
https://www.extensionmethod.net/csharp
https://csharp-extension.com/