'C# How to set Property with two arguments
I need to setup a Property with two arguments, for example, to append text in a log file. Example:
public string LogText(string text, bool Overwrite)
{
get
{
return ProgramLogText;
}
set
{
ProgramLogText = value;
}
}
How do I do this? (in the example above, I need to pass the text I want to be written in the file and 1 to overwrite (0 as default value for appending the text), else append to a text file, but when I get, I just need the text.)
Solution 1:[1]
You can extract class - implement your own class
(struct
) with Text
and Overwrite
properties and add some syntax sugar:
public struct MyLogText {
public MyLogText(string text, bool overwrite) {
//TODO: you may want to validate the text
Text = text;
Overwrite = overwrite;
}
public string Text {get;}
public bool Overwrite {get;}
// Let's add some syntax sugar: tuples
public MyLogText((string, bool) tuple)
: this(tuple.Item1, tuple.Item2) { }
public void Deconstruct(out string text, out bool overwrite) {
text = Text;
overwrite = Overwrite;
}
public static implicit operator MyLogText((string, bool) tuple) => new MyLogText(tuple);
//TODO: You may want to add ToString(), Equals, GetHashcode etc. methods
}
And now you can put an easy syntax
public class MyClass {
...
public MyLogText LogText {
get;
set;
}
...
}
And easy assignment (as if we have a property with 2 values):
MyClass demo = new MyClass();
// Set two values in one go
demo.LogText = ("some text", true);
// Get two values in one go
(string text, bool overWrite) = demo.LogText;
Solution 2:[2]
You can't.
However, you have a few possible alternative approaches: create a method, or use a Tuple instead or create a class/struct and pass as a parameter (which has been answered by someone else).
Below are some alternative methods that can also be used instead.
Alternative Method 1
Create a Tuple, but then you'd have to return a tuple string, bool.
public Tuple<string, bool> LogText
{
get; set;
}
I wouldn't do this method because then your getter would also return two values.
Alternative Method 2
Create getter and setter methods instead.
public string GetLogText() => ProgramLogText;
public void SetLogText(string text, bool overwrite) => ProgramLogText = text; // and implement in this method your use of overwrite.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 |