Drake
Drake

Reputation: 3891

C# add function or variable method to string variable

I want to be able to add my own functions and variables to the existing string variable.

Such as instead of

if(string.IsNullOrEmpty(mystring) == false)

I do this

if(mystring.isEmpty == false)

With isEmpty's get just returning isnullorempty(). This is just one of many functions I need to add to this variable to speed things up.

note* string not String

Upvotes: 1

Views: 1238

Answers (5)

Andreas
Andreas

Reputation: 6475

  1. Thats not a function, thats a property
  2. You can create new extension methods for string, but there arent extension properties in C# 4
  3. There is no difference between string and String
  4. In the .Net World isEmpty would start with a capital letter
  5. Instead of writing if (someBool == false) you should write if (!someBool)
  6. I highly question any speed improvement that you hope to see here. VS has great IntelliSense features you should learn and use those.

Upvotes: 0

Fischermaen
Fischermaen

Reputation: 12468

You can enhance every type with extension methods. But unfortunately you can only write methods, properties can not be added to a type. So if(mystring.isEmpty == false) of your sample is only working with a method like this if(mystring.IsEmpty() == false)

Upvotes: 0

Upendra Chaudhari
Upendra Chaudhari

Reputation: 6543

You need to implement extension method like below :

public static bool isEmpty(this string value)
{
    return string.IsNullOrEmpty(value); 
}

Upvotes: 0

Anand
Anand

Reputation: 14935

Use extension method. Create a static class and then declare static method(extension methods) on string like this

//this indicates you are extending method in string class

public static bool isEmpty(this string input)
{
   //your logic
}

All the linq queries have been implemented as extension methods

Upvotes: 2

siride
siride

Reputation: 209835

You'll want to use extension methods. But be careful not to make them act differently from normal methods.

Upvotes: 2

Related Questions