31

A senior member here gave me this code:

public static string Truncate(this string value, int maxChars)
{
    return value.Length <= maxChars ? value : value.Substring(0, maxChars) + " ..";
}

He said to use it as an extension method. But where do I put this method? It looks like it adds something to .Net

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
Melony
  • 1,341
  • 3
  • 10
  • 6
  • 2
    Strange that a senior programmer would give you a snippet of code without explaining how to use it or what it means. Good on you for asking, though. – Cody Gray - on strike Jul 17 '11 at 16:33
  • 2
    Cody, perhaps the senior programmer expects the author to know these things already. We don't have enough information to know whether that's a reasonable expectation or not. :) – Joe Jul 17 '11 at 16:38
  • Note that this method can cut a string in the middle of a codepoint. Not very nice. – CodesInChaos Jul 17 '11 at 16:40
  • 4
    He meant a high rep SO user, not a senior programmer on his team. See: http://stackoverflow.com/questions/6724840/how-can-i-truncate-my-strings-with-a-if-they-are-too-long/6724896#6724896 – CodesInChaos Jul 17 '11 at 16:41
  • Ah, indeed he did. Well in that case, I *strongly* suggest using the approach [Hans details in his answer](http://stackoverflow.com/questions/2903172/indicate-truncation-in-tooltipstatuslabel-automatically) to the proposed duplicate question, rather than trying to truncate the string yourself. Extension methods are nice and all, but there's a better solution here. – Cody Gray - on strike Jul 17 '11 at 16:57

4 Answers4

50

Consider a class named StringExtensions like so:

static class StringExtensions
{
    public static string Truncate(this string value, int maxChars)
    {
        return value.Length <= maxChars ? 
               value : 
               value.Substring(0, maxChars) + " ..";
    }
}

Be sure that whatever namespace you put this class in, you include a using declaration for that namespace.

Thus, for a full example:

StringExtensions.cs:

namespace My.Extensions
{
    static class StringExtensions
    {
        public static string Truncate(this string value, int maxChars)
        {       
            return value.Length <= maxChars ?
                   value :
                   value.Substring(0, maxChars) + " ..";
        }
    }
}

Program.cs:

using System;
using My.Extensions;

namespace My.Program
{
    static class Program
    {
        static void Main(string[] args)
        {
            string s = "Hello, World";
            string t = s.Truncate(5);
            Console.WriteLine(s);
            Console.WriteLine(t);
        }
    }
}

By the way, you are not adding it to .NET. You are not even adding a new method to the class String. Rather, it's a compiler trick that makes static methods living in static classes with their first parameter declared as this *TypeName* *valueParameter* where *TypeName* is the name of a type, and *valueParameter* is the name of the parameter can be made to appear as an instance method on instances of the type with type name *TypeName*. That is

string t = s.Truncate(5);

is translated by the compiler into

string t = StringExtensions.Truncate(s, 5);
Default
  • 684
  • 9
  • 19
jason
  • 236,483
  • 35
  • 423
  • 525
  • Excellent use of code to illustrate the relationship between the way one calls Extension Methods and how the compiler simply translates those calls into the way one would manually call the static method. This way, when one learns from your post, there is no "magic" that the reader must further discover. – qxotk Mar 02 '18 at 16:54
2

Put it in a static class, and use using on its namespace.

e.g.

namespace Foo
{
    static class Extensions
    {
        public static string Truncate(this string value, int maxChars)
        {
            return value.Length <= maxChars ?
                value : value.Substring(0, maxChars) + " ..";
        }
    }
}

And then in a different file:

using Foo;  //Don't forget this!

class Tester
{
    static void Test()
    {
        Console.WriteLine("123456".Truncate(3));
    }
}
user541686
  • 205,094
  • 128
  • 528
  • 886
  • Can you give me an example? I don't know what I should name the class? – Melony Jul 17 '11 at 16:32
  • 1
    [MSDN article](http://msdn.microsoft.com/en-us/library/bb383977.aspx) on extension methods might be helpful. – vgru Jul 17 '11 at 16:32
1

Yes, use a static class. I organize in a separate project that I can use across solutions. I also organize in separate files grouped by what I'm extending such as strings, enums, io, datetime, etc

Rob Allen
  • 2,871
  • 2
  • 30
  • 48
-1

In addition to other answers: yes, it's a kind of extending .NET. More strictly speaking, extending already compiled classes. You can "add" methods to the classes which are not accessible for your modification. From the internal point of view, it's just a syntactic sugar: your methods cannot be seen by reflection. But for the users of your extension, it looks as if the methods were really added to the target class (well, with some distinctions).

The possibility to influence in some way the code that is already written is an essential part of object-oriented approach. In almost any OO language you can derive from some existing class and add some functionality to it this way (although this is not the preferred way for code reusing). In Objective C, you can modify existing classes using categories at compile time. In JavaScript, you can modify them even at runtime, using prototype.

As C# is not such a dynamic language as JavaScript is, modifying the existing classes is available in a somewhat limited form of extension methods.

Vlad
  • 35,022
  • 6
  • 77
  • 199