.ToString, or other methods that use prefixes as arguments

I’m half-way decent in programming, but recently have decided to get serious.

Something I’m curious about, which I have tried Googling first before coming here, is how ToString() (or other such methods) allows you to pass an argument as a prefix instead of inside brackets. I’m use to writing functions/subs/methods where it would look like intMyVar = ToString(intMyOtherVar).

So I’m curious, how do you write a method like ToString where you can pass an argument by going argument.method(). I primarily use Visual Studio (2008 and 2010) so an example in Basic, C++, or C# would be appreciated (and I know enough about the differences to be able to translate an example in one language to another).

Thank you.

Welcome to object oriented programming.

An object is basically a set of data that’s wrapped together, and exposes some methods for interacting with that data. Often the data held within the object is kept secret from outsiders, so that the internal implementation can be changed without changing the interface. There’s no way to grab the data directly, except by asking for it, which is what the ToString() function is effectively doing.


class Foo {
   private int myData = 42; // can't be accessed from the outside. It's private

   public String ToString() { // can be accessed from the outside. It's public
      return ("Foo: " + myData);
   }
}

Are you asking how to write a class? That’s what you’re talking about if you’re wondering about the ToString() method - it’s a method of the String class. It’s not using the prefix as an argument (though it’s easy to see how you’d think that), it’s that the prefix is a variable of the type String, and therefore has access to class methods like ToString().

If you’re not familiar with class design, that’s a bit more than can be really answered on a forum like this. It’s not overly difficult, but you’ll want a tutorial that shows you the ins and outs and gotchas. You need to learn about inheritance and scope and properties and methods.

There’s a good start here and a tutorial here.

In the case of C++, it actually is an argument to the method when it gets compiled (so far as I’ve ever seen). The compiler considers the data to be a C-style struct and all methods which act as methods on that object to be functions which take a struct of that type as their first argument. I suspect that most other compilers and interpreters do the same thing.

Seeing the answers you’ve already gotten so far, I’m going to go out on a limb and guess you’re actually asking something else that’s not easily articulated into words. However, based on the words you did write, I’m thinking what you’re after is a C# language feature called “extension methods.”

The reason I guess you want exension methods is because you happen to choose a universal method such as .ToString() that seemingly operates on everything to the left of that dot. Hydrogen.ToString() and Oxygen.ToString(), MickeyMouse.ToString() and so on.

The way to get that type of syntax equivalent is to create a base object at the top of a class hierarchy (unrealistic) or use extension methods. C++ doesn’t have a syntax equivalent – unless you do funky meta techniques with templates.

Extension methods mean extending an already-written class (e.g. one you don’t have the source to) by adding new methods. They do not allow you to add “universal” methods to everything - the same inheritance rules apply. ToString and the like are declared in Object in C#.

I didn’t say that extension methods add a universal method to everything – although one could get close to it with abuse of the language feature using type Object such as


public static bool foobar (this object) {};  

What I said was that the OP himself happen to choose an example where .ToString() seems to operate universally on everything which makes me think he’s looking for the C# feature of extension methods.

Look at the kind of question the OP was asking and see if extension methods is what he’s looking for.

What inheritance rules are you talking about? If he constructs an extension method with a type argument that’s high enough in the type hierarchy (such as Object), the question of “inheritance rules” is not really a roadblock.

Yes. It’s an implicit parameter named “this”, of type “pointer to an instance of this class”.

Java also has “this”, and it has similar usage to C++. (Though Java has only references, not pointers in the C++ sense.)

Python has a “this”, although it’s normally called “self”, and you must supply it explicitly in the argument list of your method’s definition. The name “self” is only a convention though, not a keyword of the language, so theoretically you can name it whatever you want.

Of course. But I’m guessing this is not what the OP had in mind when asking his question.

One mistake. I just looked at the official documentation and it looks like ToString is only present in Visual Basic and C#, not C++ (or F# or JScript).

Breaking it down, it seems to go like this.
The namespace is System.
The class is Object.
The method is ToString.

My question is this.
OK, say I do:



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class TC
{
    public int Add1(int passVar)
    {
        return passVar + 1;
    }
}
namespace CSharp_Test
{
    class Program
    {
        static void Main(string[] args)
        {
            int iVar1 = 0, iVar2 = 0;
            TC A1 = new TC();
            iVar1 = A1.Add1(iVar2);
        }
    }
}


That works.
But, is there a way I could make Add1 so that I could do this:
iVar1 = iVar2.Add1(); :confused:

You’ve got to realize that, conceptually, you are creating a method for the object, not passing a parameter. The whole concept of dot (.) notation is that anything following the dot is inside whatever precedes it. What you do is create (or extend) the class of the object you want to mess with, and include the function in the class so it will automatically pass to the object.

The only language I can demonstrate in is JavaScript (aka JScript), since it’s the only one with which I am familiar. Unfortunately, JavaScript is really a classless language, so it may not help. Using functions as classes is really just a work around.

In JavaScript, you extend the class’s prototype. You’d likely create a special new class of integer, and then add the function to the prototype, and only then make the new integer. Something like

function Int2 (param) { this.num = param; return this.num; }  // using function as a class
Int2.prototype.add1 = function() {return this.num + 1};
var iVar1 = new Int2(5);
alert (iVar1.add1());

You also could extend the Number class itself (though it would not be considered best practice):

Number.prototype.Add1 = function() {return this + 1};
var iVar1 = 5;
alert (iVar1.Add1())

Both of these will return “6” in an alert box.

Even if I were to look up C# examples, I’m not sure I’d feel comfortable submitting them without being able to test them first. But I hope the JavaScript examples will help get the concept through.

I pointed it out in case he was coming from C.

Sure, though that’s sort of wonky.


class Foo {
   private int i;

   public Foo(int value) { // constructor
      i = value;
   }

   public Foo Add1() {
      return new Foo(i + 1);
   }
}

That is, assuming that Foo is a class which simply wraps an integer value.

What the OP’s post #10 is describing is exactly what .Net calls “extension methods” as described by Ruminator. So this would work in C# v3.0 & later:


using System;
public static class ExtensionMethods
{
    public static int Add1(this int passVar)
    {
        return passVar + 1;
    }
}
namespace CSharp_Test
{
    class Program
    {
        static void Main(string[] args)
        {
            int iVar1 = 0, iVar2 = 0;
            iVar1 = iVar2.Add1();
        }
    }
}

It’s the “this” in the parameter declaration of the Add1 method which signals that the method is an “extension method” and may be called as shown in the Program class.

There are a couple of caveats here.

  1. I’m not 100% certain extension methods work on value types, such as int & float. A quick look at Ruminators’ msdn link didn’t answer the question.

  2. This code only extends the System.Int32 type. You’d need to define a similar Add1 method for each of the other primitive numeric data types, such as Int16, Int64, Uint32, Float, etc.

  3. All you’re doing is creating what we call “syntactic sugar”, a different notation to acheive the same result. The Add1 I defined above works under the covers pretty much identically to the way the one the OP defined in his post #10. Had you defined your TC class & Add1 method as as static our two solutions would be identical under the covers. These translations are going on behind the scenes and may not matter to the OP unless he/she tries to think more deeply about the innards.

  4. In actual use, you’d want to put the ExtensionMethods class in its own namespace. Then all other code which intends to use the methods of that namespace *must *contain a using statement referencing that namespace. In fact I suspect the code I wrote above won’t quite compile due to that.

  5. As msdn says, this capability should be used sparingly. You run the risk that a later version of the class you’re syntactically extending may add a method of the same name as your own. When that happens, the new built-in method will start being used instead and all your deployed running code will break. So do not go around willy-nilly extending foundational .Net classes is some misguided pursut of syntactic consistency.

  6. AFAIK, extension methods can only be written in VB or C#. Once compiled, they can be used by any .Net language.

See How to implement and call a custom extension method - C# Programming Guide | Microsoft Learn for more.

It’s a good idea to override the ToString method in your own objects in order to provide more useful data for debug purposes, BTW.

Thank you all for your help. It was much appreciated.