[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

microsoft.public.dotnet.framework.sdk

Emulating/Implementing String.Format()

Gabriel Gonzalez

10/3/2002 2:09:00 PM

Hello,

I am writing a class for which it would be ideal for me to
implement a method that behaves just like String.Format().

I would like to do this, in a nutshell (in C# parlance):

public void DoSomething(int a, string b, string Format [,
variable list of arguments]);

I know I can get away with this (which is what I have
right now):

public void DoSomething(int a, string b, string Msg);

But that forces the caller to call it this way:

MyClass.DoSomething(1, "whatever", String.Format("{0} is
good", StrVar));

I would much rather have it called this way:

MyClass.DoSomething(1, "whatever", "{0} is good", StrVar);

Of course, the whole problem is how to declare and use an
undefined number of parameters, or maybe there is
something in the .NET framework that make this specific
thing easier/possible to write.

Thanks for your help.
2 Answers

MikeB

10/3/2002 4:30:00 PM

0


"Gabriel Gonzalez" <gab@gab.com> wrote in message
news:1101b01c26ade$2be929a0$3aef2ecf@TKMSFTNGXA09...
> Hello,
>
> I am writing a class for which it would be ideal for me to
> implement a method that behaves just like String.Format().
>
> I would like to do this, in a nutshell (in C# parlance):
>
> public void DoSomething(int a, string b, string Format [,
> variable list of arguments]);
>
> I know I can get away with this (which is what I have
> right now):
>
> public void DoSomething(int a, string b, string Msg);
>
> But that forces the caller to call it this way:
>
> MyClass.DoSomething(1, "whatever", String.Format("{0} is
> good", StrVar));
>
> I would much rather have it called this way:
>
> MyClass.DoSomething(1, "whatever", "{0} is good", StrVar);
>
> Of course, the whole problem is how to declare and use an
> undefined number of parameters, or maybe there is
> something in the .NET framework that make this specific
> thing easier/possible to write.

You can pass variable paramters to a method in C# using the 'params'
keyword. Your method declaration would look something like:

public void DoSomething(int a, string b, string format, params object[]
varparams);

Happily, String.Format has an overload that takes a params array, so inside
your method you should be able to call it like so:

formattedstring = String.Format( format, varparams);


>
> Thanks for your help.

--
MikeB



Gabriel Gonzalez

10/4/2002 1:12:00 AM

0

>You can pass variable paramters to a method in C# using
the 'params'
>keyword. Your method declaration would look something

Ahhh, it seems I have a case of "RTFM"! Thanks for
pointing this out... Somehow I missed the whole params
keyword in my initial search.

Thank you.