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
}
Related
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('%');
The next methods are inside a class A inheriting from List< Class B >:
// Method A: Updates from specified start to end of list.
public void UpdateItems(int start = 0) {
UpdateItems (
Enumerable.Range (start, this.Count - start).ToArray ()
);
}
// Method B: Updates separate indexes when necessary.
public void UpdateItems(params int[] indexes) {
foreach (int i in indexes)
this [i].id = i + 1;
}
Sometimes is necessary to update item properties(e.g. public int id) on different indexes and sometimes I just need a start-index and update from it to the end of the list. I came up with this simple two methods and everything was fine until I needed to use a simple param for params in method B, which was used as start for method A. I knew this was coming for they share the same name, still I wanted to test.
Questions:
What is the best way to deal with this kind of cases? (i.e. You have overloaded methods for (params T[]) and (T param)). I know a simple name change is enough but I'd like a deeper opinion/solution.
How is the overload resolution done?
Actually you can call the method with param name, for example
UpdateItems(indexes: 1); //Will call method with params
UpdateItems(1); //Will call method with start index
but in my opinion this is not a good solution. Would be better to have two methods with different names.
Also another way to call method with params would be passing array of integers as a method parameter
UpdateItems(new [] {1});
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
I am used to using functions that return a single value "in-line" like so:
Label1.Text = firstString + functionReturnSecondString(aGivenParameter);
Can this be done for a function that returns two values?
Hypothetical example:
label1.Text = multipleReturnFunction(parameter).firstValue
I have been looking into returning more than one value and it looks like the best options are using a tuple, struct, or an array list.
I made a working function that retuns a struct. However the way I got it to work I need to first call the function, then I can use the values. It doesn't seem possible to make it happen all on the same line without writing another function.
multipleReturnFunction(parameter);
Label1.Text = firstString + classOfStruct.secondString;
I haven't made a function that returns a tuple or array list yet, so I'm not sure. Is it possible to call those functions and reference the return values "inline"?
I appreciate your feedback.
I have a grotty hack for exactly this type of scenario - when you want to perform multiple operations on the return value without defining an extra variable to store it:
public static TResult Apply<TInput, TResult>(this TInput input, Func<TInput, TResult> transformation)
{
return transformation(input);
}
... and here's the reason it came about in the first place:
var collection = Enumerable.Range(1, 3);
// Average reimplemented with Aggregate.
double average = collection
.Aggregate(
new { Count = 0, Sum = 0 },
(acc, i) => new { Count = acc.Count + 1, Sum = acc.Sum + i })
.Apply(a => (double)a.Sum / (double)a.Count); // Note: we have access to both Sum and Count despite never having stored the result of the call to .Aggregate().
Console.WriteLine("Average: {0}", average);
Needless to say this is better suited for academic exercises than actual production code.
Alternatively, use the ref or they out keyword.
Example:
int a = 0, b = 0;
void DoSomething(ref int a, ref int b) {
a = 1;
b = 2;
}
Console.WriteLine(a); // Prints 1
Console.WriteLine(b); // Prints 2
It's not inline and I personally would consider a class or a struct before using the ref or the out keyword. Let's consider the theory: when you want to return multiple things, you have in fact an object that has multiple properties which you want to make available to the caller of your function.
Therefore it is much more correct to actually create an object (either by using a class or a struct) that represents what you want to make available and returning that.
The only time I use the ref or the out keyword is when using DLL imports because those functions often have pointers as their calling arguments and I personally don't see any benefit in using them in your typical normal application.
To do this inline, I think you would have to have another method that takes your struct and gives you the string you are looking for.
public string NewMethod(object yourStruct)
{
return string.Format("{0} {1}", yourStruct.value1, yourStruct.value2);
}
Then in the page, you do this:
Label1.Text = NewMethod(multipleReturnFunction(parameter));
C# doesn't have Inline functions, but it does support anonymous functions which can be closures.
With these techniques, you can say:
var firstString=default(String);
var secondString=default(String);
((Action<String>)(arg => {
firstString="abc"+arg;
secondString="xyz";
}))("wtf");
label1.Text=firstString+secondString;
Debug.Print("{0}", label1.Text);
((Action<String>)(arg => {
firstString="123"+arg;
secondString="456";
}))("???");
label1.Text=firstString+secondString;
Debug.Print("{0}", label1.Text);
or name the delegate and reuse it:
var firstString=default(String);
var secondString=default(String);
Action<String> m=
arg => {
firstString="abc"+arg;
secondString="xyz";
};
m("wtf");
label1.Text=firstString+secondString;
Debug.Print("{0}", label1.Text);
m("???");
label1.Text=firstString+secondString;
Debug.Print("{0}", label1.Text);
So, do you really need a method returns multiple values?
Each method can return only one value. Thats how methods defined in .NET
Methods are declared in a class or struct by specifying the access
level such as public or private, optional modifiers such as abstract
or sealed, the return value, the name of the method, and any method
parameters
If you need to return more than one value from method, then you have three options:
Return complex type which will hold all values. That cannot help you in this case, because you will need local variable to store value returned by method.
Use out parameters. Also not your case - you will need to declare parameters before method call.
Create another method, which does all work and returns single value.
Third option looks like
Label1.Text = AnotherMethod(parameters);
And implementation
public string AnotherMethod(parameters)
{
// use option 1 or 2 to get both values
// return combined string which uses both values and parameters
}
BTW One more option - do not return values at all - you can use method which sets several class fields.
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.