Click here to Skip to main content
15,891,316 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi
Let say I have a class which looks something like this:
public class MyClass
{
public static readonly string MyObject = "Myobj.ClientName";
}


I'm not going to dive into why things are the way they are... this is what I have to work with. Thing is, I need only the bit after the '.' so I use substring to get all string after the '.'. In other places in the application the entire string is used as is.

I want to do this in a simpler form. I want to do something like this:
MyClass.MyObject.ToShort();


So it will work a lot like .ToString and only return something specific.

How can I add .ToShort to the class??

Any help would be appreciated.
Thanks
Posted

Since you are using .NET 3.5, there is a way to create extension methods that can be used against strings. In your case it would be something like:
C#
public static string ToShort(this string s)
{
    return s.Substring( 6 );
}


The key here is the this identifier in the parameter. Code sample derived from this[^] article by Mike Gold.
 
Share this answer
 
Comments
NeCroFire 23-Nov-10 3:00am    
This looks like it will work. Only thing is that everything needs to be static which should be fine for what we're doing.

Thanks
Sunasara Imdadhusen 23-Nov-10 23:43pm    
Good answer!!
Sunasara Imdadhusen 23-Nov-10 23:43pm    
Take 5 from me!
Hi
you have to add following method like

C#
public static string ToShort(string strsql)
{
   return "";
}

//you can access 
MyClass.ToShort(MyClass.MyObject);
 
Share this answer
 
Yes you can add ToShort, try coding it.

you may also override ToString if you want to
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900