Payson Welch
Payson Welch

Reputation: 1428

Default method for C# class

Hi is it possible to specify a method that is the default method for a C# class? I am writing a short class to output embed code for a video, here is the basic idea:

 public class EmbeddedVideo
{
    public string VideoPath { get; set; }
    public string ImagePath { get; set; }

    public string EmbedCode()
    {
        return "...";
    }
}

Now if I were to say:

Response.Write(new EmbeddedVideo());

It would output the result of the GetType() method. How can I specify that I would like the EmbedCode() method to be the default in this context?

Upvotes: 1

Views: 1413

Answers (2)

BoltClock
BoltClock

Reputation: 723688

Override ToString(), which gets called in many scenarios where string conversion takes place:

public override string ToString()
{
    return EmbedCode();
}

The "default" you're referring to is the default implementation of Object.ToString(), which simply happens to return the type name:

The default implementation returns the fully qualified name of the type of the Object.

Upvotes: 13

JaredPar
JaredPar

Reputation: 754763

It sounds like by "default method" you mean "method which controls how instances of the type are displayed in methods like Write." If so what you want to do is override the ToString method.

public override string ToString() {
  return EmbedCode();
}

Upvotes: 2

Related Questions