is there shorter way of calling non static method in c#? - c#

I have a class StringFormatter which contains method RemoveCharFromString.
For a long time, I have been creating a new instance of a class and then use it like the following:
[...]
StringFormat sf = new StringFormat();
string exampleString = sf.RemoveCharFromString(inputString, '%');
[...]
Now I came to a point where I just have to use this method a single time in one class. I thought there might be a shorter way of accomplishing the above code such as:
[...]
string exampleString = new StringFormat.RemoveCharFromString(inputString, '%');
[...]
Is there something for that?

You can instantiate a class and call one of it's methods directly - your second code sample just needs a parenthesis after the constructor:
string exampleString = new StringFormatter().RemoveCharFromString(inputString, '%');
However - there are things to consider here, without knowing the insides of the method:
The method's name suggests it's basically removing a specific char from the string - If it removes all occurrences of said char, why not just use string.Replace()?
Since this method seems to be getting all the information it needs from it's arguments and does not rely on, nor changes the state of the StringFormatter instance, why not make it a static method?

Sounds to me like the StringFormatter class is a bunch of methods which works on the type string. One option, could therefore be to consider to use extensions methods on the string type instead
public static class StringFormatter
{
public static string RemoveCharFromString(this string value, char charToRemove)
{
//do your logic and then return a string
}
}
Then use it
var exampleString = inputString.RemoveCharFromString('%');

Related

Passing 156 character string to multiple functions

I have a c# winforms .net 4 application which receives a 156 character message I then pass this message unchanged to multiple function in turn.
My question is is it inefficient to keep passing the same value as a parameter or is there a more efficient way?
so currently I have :
string code = getTheCode();
\\decode first part
string result1 = getResult1(code);
string result2 = getResult2(code);
...
value of code never changes after its initial assignment.
The answer is no. It is not inefficient to keep passing the same string as a parameter. You are just passing a reference to the string, so it is very efficient.
You could create a class with a constructor requiring you to pass your string as argument and set it as a private property. Then you could retrieve data using methods which would use this private property to calculate results.
But this is only a matter of coding style you prefer, of course (and whether you will use these methods in one or more places). For me it's more readable AND you get to make sure that code variable won't change in that instance of ResultGetter class.
public class ResultGetter
{
private readonly string _code;
public ResultGetter(string code)
{
_code = code;
}
public string GetResult1()
{
var returnValue = // do something with _code property
return returnValue;
}
public string GetResult2()
{
var returnValue = // do something with _code property
return returnValue;
}
// et cetera ad nauseam
}
And then in your main file:
var code = getTheCode();
var rg = new ResultGetter(code);
string result1 = rg.GetResult1();
string result2 = rg.GetResult2();
It may be inefficient to keep passing the same code to several methods. If you find you have to do this many times, you might want to create a class responsible for 'getting results'. Pass the ''code' in the constructor of this new class. This way you can reuse the 'code' during the lifetime of the class and you don't have to keep passing the same value as a parameter

ToString method and return static string

Class example:
public class SomeType
{
private int type;
// some code...
public override string ToString ()
{
if (type == 1) return "One";
if (type == 2) return "Two";
}
}
Now imagine application calls thousand times ToString() method in a second.
My question is: when I use inline created string in code like something = myClass.ToString() is in every call created a new string or compiler optimize it somehow? (because strings are immutable it could be returned only referense to a static string).
And if not, should I make static private string fields and return them in ToString method for performance reasons?
Ofcourse I will test it using Stopwatch, but I need an expert answer anyway.
You're using string literals - which means you're returning a reference to the same string each time. This is guaranteed by the language specification. From section 2.4.4.5 of the C# 5 specification:
When two or more string literals that are equivalent according to the string equality operator (ยง7.10.7) appear in the same program, these string literals refer to the same string instance.
So as a simpler example:
string x = "One";
string y = "One";
Console.WriteLine(object.ReferenceEquals(x, y)); // Prints True
In your code, the ToString() method will still be called - but it won't create a new string object each time. You might consider using a switch statement instead of all those if statements, by the way.
Note that even if it did create a new string each time, creating thousands of strings per second won't make a modern CPU break into a sweat. Both the allocator and garbage collector are pretty efficient, and modern computers can do an awful lot of work in a second.

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
You'll want to use extension methods. But be careful not to make them act differently from normal methods.
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
You need to implement extension method like below :
public static bool isEmpty(this string value)
{
return string.IsNullOrEmpty(value);
}
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)
Thats not a function, thats a property
You can create new extension methods for string, but there arent extension properties in C# 4
There is no difference between string and String
In the .Net World isEmpty would start with a capital letter
Instead of writing if (someBool == false) you should write if (!someBool)
I highly question any speed improvement that you hope to see here. VS has great IntelliSense features you should learn and use those.

C# - Using a methods string in another method

I currently have a method that removes duplicates from a line, although the output is currently going into a new file. How could I instead use the output as a string and then use it in another method:
Well, you can store the return value of the first method in a variable and pass it to the second method (after modifying the second to accept an argument):
var str = RemoveDuplicate(someValue, someOtherValue);
CompareFiles(str);
The second method would need to be defined with an argument:
private static void CompareFiles(string someValue)
{
// implementation
}

Store a reference to a string

I have a class that has 3 string properties. I want to store these in a list so that when I make changes to the strings of the list they also get updated in the class.
This would be easy to do if I was using class object, but string seems to behave differently. It seems to make a copy of the object for the list rather then have a pointer to the object. How am I supposed to do this is C#? If this is not possible is there a better way?
The problem with strings is that they are immutable. In other words, you can never change a string once it is created.
Thus, if you want to 'change' a string, you must remove the original from the List, and store the result back into the list. Example:
string a = "abcdefg";
List<String> list = new List<String>();
list.add(a);
a = a.Substring(0, 5);
That code does nothing because the string a is pointing to never changes. It just points to a new string.
In .NET, strings are immutable. If you change the string, you are in fact creating a new one and modifying the reference.
I would consider using a StringBuilder object to address your problem.
Strings are immutable. You can change a reference to point to another string but you cannot modify a string such that other references to it change value as well (except by unsafe, completely dangerous reflective code)
What you want to do is deal with this either through using a mutable alternative, (such as a StringBuilder) or via explicit indirection. I'll show you the latter:
public class Props
{
private readonly string[] data = new string[2];
public string Foo {
get { return data[0]; }
}
public string Bar {
get { return data[1]; }
}
public IList<string> ModifyValueButNoInsertsList { get { return data;} }
}
Really you should consider actually using string[] rather than IList in this situation as it makes it clear inserts are forbidden, only alterations of the values. Since string[] implements IList<string> this is unlikely to be a problem
Since strings are immutable, the simplest work-around is to instead store the reference to a string array with one element. Replacing that element will then be noticed by anyone with a reference to the array.
Strings in C# are immutable, so you cannot change a string in C# - you can only create new strings.
You could rather store a class that has a string member
class StringHolder {
public StringHolder(string s) { str = s;}
public string str;
}
...
List<StringHolder> l1 = new List<StringHolder>();
List<StringHolder> l2 = new List<StringHolder>();
List<StringHolder> l3 = new List<StringHolder>();
StringHolder h = new StringHolder("Test\n");
l1.add(h);
l2.add(h);
l3.add(h);
h.str = h.str.Replace("\n","");
Now all lists refer to the same StringHolder and will naturally see the same string.
Another option is to store StringBuilder objects in your lists instead of a String.
class StringHolder
{
public string Value { get; set; }
}
Keep a list of those instead of just strings. Then you can get/set the Value property to update the string value.
You're looking for a mutable string of some kind. There are a lot of ways to create a class that behaves the way you want it.
The easiest way would be to use a StringBuilder object instead of a string. You just have to be careful to not make new StringBuilder objects, but rather alter the existing one. Depending on what you need, this may not be the best option.
Alternatively you can create your own wrapper class for String that you can manipulate freely. The downside is you may have to write a lot of stub methods that call down to the inner string depending on how you want to use it. It would be easier to just expose a read/write string property. This has the advantage of letting you define exactly what behaviours you want, but will take longer to write in the first place. Again, you'll have to make sure to not create new instances of the wrapper class, but rather just alter the class's internal string.
Wrap your string into a custom class, this will allow you to share it amongst a number of different locations. You could also choose to store Char arrays instead.
As a side note (like several have mentioned), if you're doing some heavy processing with strings, use the StringBuilder class. Because of the immutable nature of strings, changing/concatenation of them in loops or what have you - will cause a lot of overhead.
StringBuilder is your friend.

Categories