Foxy
Foxy

Reputation: 1146

How to add methods and fields to literal objects?

In object-oriented programming, everything is supposed to be an object. Starting from this postula, is it possible to add methods and fields to a literal object, such as a number, a string, a Boolean value or a character?

I noticed that in C#, we can use some methods and fields of the "Integer" class from a mathematical expression:

var a = (2 + 2).ToString();

I imagine that it is more syntactic sugar to access the "Integer" class and a method actually related to the mathematical expression (and / or its value).

But is it possible in C# to define one of the methods and fields to a literal object alone? Such as these examples:

"Hello, world!".print();
var foo = 9.increment();

This would probably be useless, but the language being object-oriented, this should be feasible. If this is not possible in C#, how could we do this with the object-oriented paradigm?

Upvotes: 1

Views: 412

Answers (4)

akerra
akerra

Reputation: 1210

You can use extension methods to achieve this, which must be static methods defined in a static class. In you example above, you could do the following:

public static class Extensions
{
    public static int increment(this int num)
    {
        return ++num;
    }
}

Upvotes: 0

Servy
Servy

Reputation: 203830

You don't add methods to a given instance of an object, you add methods to a type. Additionally, the language doesn't allow you to define what methods a string (or other type of) literal has, it defines what methods all strings have, of which string literals act just like any non-literal strings, and have exactly the same methods.

Note that (2 + 2) is not an instance of the "Integer" class, it will resolve to an instance of the System.Int32 struct. The difference isn't relevant to this behavior, but it's relevant to lots of others.

Upvotes: 1

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186813

Sure, you can implement an extension method and have the desired syntax (however, Int32 class will not be changed):

  public static class IntExtensions {
    public static int increment(this int value) {
      return value + 1; 
    }
  }

 ...

 // Syntax sugar: the actual call is "int foo = IntExtensions.increment(9);"
 var foo = 9.increment();

In the current C# version (7.2) we can't add extension properties, extension events etc. These options can appear in C# 8.0 (Extension everything, https://msdn.microsoft.com/en-us/magazine/mt829270.aspx):

Upvotes: 4

Brandon Paris
Brandon Paris

Reputation: 13

"Hello, world!".print();

This string is an instance of the String Class in C# which inherits from the Object class. So you have to create the print() method in the String Class in order to make this work.

Upvotes: 0

Related Questions