Passing list of defined values as parameter C# - c#

How can I make my method have defined list of values that can be passed. I've seen this in VB.net, but can't find it in C#, and it dosen't look like enum.
class Test
{
List { active, all, completed}
public string get(string a, List b)
{
// some code
}
string a = get("foo", active);
string b = get("foo", all);
}

If enum is called test, I need to pass test.active and I don't want that. I need to pass only active
What you can do is use the using static keyword when you want to use the enum, then you can just use the word you want.
namespace Foo
{
class Test
{
public string get(string a, List b)
{
// some code
}
}
public enum List { active, all, completed}
}
used like
using Foo;
using static Foo.List;
public void Example()
{
var test = new Test();
//Because of "using static Foo.List;" you don't need to use "List.active"
string a = test.get("foo", active);
string b = test.get("foo", all);
}

Related

What is the use of "this" in Java and/or C#? [duplicate]

This question already has answers here:
When do you use the "this" keyword? [closed]
(31 answers)
Closed 9 years ago.
Say I have a simple sample console program like below. My question is in regards to this. Is the sole use of this just so you can use the input variable name to assign to the instance variable? I was wondering what the use of this is other than used in the context of this program?
public class SimpleClass {
int numberOfStudents;
public SimpleClass(){
numberOfStudents = 0;
}
public void setStudent(int numberOfStudents){
this.numberOfStudents = numberOfStudents;
}
public void printStudents(){
System.out.println(numberOfStudents);
}
public static void main(String[] args) {
SimpleClass newRandom = new SimpleClass();
newRandom.setStudent(5);
newRandom.printStudents();
}
}
Previously, when I needed to assign a value to an instance variable name that shares similarities to the input value, I had to get creative with my naming scheme (or lack of). For example, the setStudent() method would look like this:
public void setStudent(int numberOfStudentsI){
numberOfStudents = numberOfStudentsI;
}
From that example above, it seems like using this replaces having to do that. Is that its intended use, or am I missing something?
Things are quite the opposite of how you perceive them at the moment: this is such an important and frequently used item in Java/C# that there are many special syntactical rules on where it is allowed to be assumed. These rules result in you actually seeing this written out quite rarely.
However, except for your example, there are many other cases where an explicit this cannot be avoided (Java):
referring to the enclosing instance from an inner class;
explicitly parameterizing a call to a generic method;
passing this as an argument to other methods;
returning this from a method (a regular occurrence with the Builder pattern);
assigning this to a variable;
... and more.
this is also used if you want to a reference to the object itself:
someMethod(this);
There is no alternative to this syntax (pun intended).
It's also used to call co-constructors, and for C# extension methods.
'this' simply refers to the object itself.
When the compilers looks for the value of 'numberOfStudents', it matches the 'closest' variable with this name. In this case the argument of the function.
But if you want to assign it to the class variable, you need to use the 'this.'-notation!
In the method
public void setStudent(int numberOfStudents){
this.numberOfStudents = numberOfStudents;
}
for example.
'this.numberOfStudents' references the class variable with the name 'numberOfStudents'
'numberOfStudents' references the argument of the method
So, this method simple assigns the value of the parameter to the class variable (with the same name).
in c# you use this to refer the current instance of the class object immagine you have class like this from msdn
class Employee
{
private string name;
private string alias;
private decimal salary = 3000.00m;
// Constructor:
public Employee(string name, string alias)
{
// Use this to qualify the fields, name and alias:
this.name = name;
this.alias = alias;
}
// Printing method:
public void printEmployee()
{
Console.WriteLine("Name: {0}\nAlias: {1}", name, alias);
// Passing the object to the CalcTax method by using this:
Console.WriteLine("Taxes: {0:C}", Tax.CalcTax(this));
}
public decimal Salary
{
get { return salary; }
}
}
class Tax
{
public static decimal CalcTax(Employee E)
{
return 0.08m * E.Salary;
}
}
class MainClass
{
static void Main()
{
// Create objects:
Employee E1 = new Employee("Mingda Pan", "mpan");
// Display results:
E1.printEmployee();
}
}
/*
Output:
Name: Mingda Pan
Alias: mpan
Taxes: $240.00
*/
You have different scopes of variables in Java/C#. Take this example below. Although this.numberOfStudents and numberOfStudents have the same name they are not identical.
public void setStudent(int numberOfStudents){
this.numberOfStudents = numberOfStudents;
}
this.numberOfStudents is a variable called numberOfStudents that is in the instance of this class. this always points on the current instance.
public void setStudent(int numberOfStudents) that numberOfStudents is a new variable that is just available in this method.
keyword "this" refers to an object of the current class (SimpleClass) on the fly.
public class SimpleClass(){
private int a;
private int b;
private int c;
public SimpleClass(int a, int b){
this.a = a;
this.b = b;
}
public SimpleClass(int a, int b, int c){
// this constrcutor
this(a,b);
this.c = c;
}
}

How to specify defaults for a plugin function in C#

I'm trying to implement a simple plugin system which will allow people to write the following:
[Plugin("A plugin function")]
public static int PluginFunction(int a, int b)
{
return a + b;
}
and then drop the DLL containing this function into a folder where it will be scanned by the application and show up as an available function at runtime. This all works fine, so far so good, the PluginAttribute class is what you would expect, just a description string for the function.
However, I'd like to allow the plugin writer to specify default values for the parameters. This is OK for values which are constant at compile time and then deduced via reflection, but I'd like a way to specify defaults for more complex types which will be created at runtime. Has anyone implemented something similar? The primary goal is to make it simple to implement plugin functions - I'm trying to avoid complex scaffolding but accept that my nice simple system is not going to cut it if I want this feature. I'm also happy to have some complexity in the application code which makes the system appear simple to the plugin writer.
Thanks,
Charlie.
Update:
I'm going with a combination of what's been suggested here, the closest is what Peter O. came up with - here's a version:
[Plugin("A plugin function")]
[Defaults(typeof(AdderDefaults))]
public static int Adder(int a, int b)
{
return a + b;
}
public static class AdderDefaults
{
public static int a { get { return 1; } }
public static int b { get { return 2; } }
}
[Plugin("Another plugin function")]
[Defaults(typeof(TexturizerDefaults))]
public static Bitmap Texturize(Bitmap source, Point offset)
{
return result;
}
public static class TexturizerDefaults
{
// no default for source parameter
public static Point offset { get { return new Point(16, 16); } }
}
This allows parameters to be skipped and specified by name. No compile time checking but that's OK - checking these at runtime is acceptable.
Maybe you can create an attribute which refers to a type
containing default values for the plugin. Example:
[PluginDefaults(typeof(MyPluginDefaults))]
The class MyPluginDefaults could then look like:
public class MyPluginDefaults {
int Parameter1 { // First parameter
get { return 0; } // default value for 'a'
}
int Parameter2 { // Second parameter
get { return 4; } // default value for 'b'
}
// Additional parameters would be called Parameter3, Parameter4, and so on.
}
There are lots of way to do that, the simpliest is to use a simple convention :
[Plugin("A plugin function")]
public static int PluginFunction(int a, int b)
{
return a + b;
}
public static object[] PluginFunctionDefaultArguments()
{
return new [] { 0, 0 };
}
Each time you find a function marked with PluginAttribute search for a function having the same name with the DefaultArguments sufix, no parameters and an object[] return type. Then call it and store the values somewhere. You should also support the default values to be specifed using the dedicated C#/VB syntax (it is found in the DefaultValue member for the parameter)
One way would be to have property Defaults for each of the classes. It returns an object that can be queried for the defaults, for example like this:
object[] pluginFunctionDefaults = FooPlugin.Defaults["PluginFunction"];
(Obviously, you wouldn't have code exactly like this in your application.)
And the declaration of the defaults could look like this:
class FooPlugin
{
static FooPlugin()
{
var bar = new Bar();
Defaults = new DefaultValues()
.Add(() => PluginFunction(42, 13))
.Add(() => AnotherFunction(bar));
}
public static DefaultValues Defaults { get; private set; }
// actual methods of the class
}
Using expressions like this means that the types of the defaults are checked at compile time. The DefaultValues class parses the expressions and stores the parameters. It could look something like this:
class DefaultValues
{
private readonly Dictionary<string, object[]> m_expressions =
new Dictionary<string, object[]>();
public DefaultValues Add<T>(Expression<Func<T>> func)
{
var methodCall = ((MethodCallExpression)func.Body);
var name = methodCall.Method.Name;
var arguments =
methodCall.Arguments
.Select(Evaluate)
.ToArray();
m_expressions.Add(name, arguments);
return this;
}
private static object Evaluate(Expression expression)
{
return Expression.Lambda<Func<object>>(
Expression.Convert(expression, typeof(object)))
.Compile()();
}
public object[] this[string methodName]
{
get { return m_expressions[methodName]; }
}
}

Access property by Index

I need to access a property by an index or something similar. The reason why is explained in this already answered question. That answer uses Linq and I prefer something without that dependency. I have no control over the class.
public class myClass
{
private string s = "some string";
public string S
{
get { return s; }
}
}
class Program
{
static void Main(string[] args)
{
myClass c = new myClass();
// I would like something similar
// or same functionality
string s = c["S"];
}
}
As you have no control over the class you can use extension method and reflection to get property value by name:
static class ObjectExtensions
{
public static TResult Get<TResult>(this object #this, string propertyName)
{
return (TResult)#this.GetType().GetProperty(propertyName).GetValue(#this, null);
}
}
Usage:
class A
{
public string Z
{
get;
set;
}
public int X
{
get;
set;
}
}
class Program
{
static void Main(string[] args)
{
A obj = new A();
obj.Z = "aaa";
obj.X = 15;
Console.WriteLine(obj.Get<string>("Z"));
Console.WriteLine(obj.Get<int>("X"));
Console.ReadLine();
}
}
use (EDIT - as per comment):
string s = c.GetType().GetProperty ("S").GetGetMethod().Invoke (c, null).ToString();
It gives you the value of the (public) property named S of the the instance c regardless of the type of c and doesn't use LINQ at all although I must admit that I don't see why LINQ should be a problem...
You can achieve the same thing by using a default property on your class and a collection. Provided that you will always want strings, you could use the Dictionary class as your default property.
Then in the constructor you could intialize myDictionary["s"] = "some string";
You could then use the myClass as a collection, so myClass["s"] would return "some string".
Reflection is usually an indicator that you haven't created an API to do the job you need, if you have the code to modify then I recommend you use the default property.
See this MSDN article:

C# call method on a member class

I want do something like that:
public class MyClass
{
public String varA{ get; set; }
public String[] varB{ get; set; }
//.....
public ?? string ToHtml()
{
//return HTML value
}
}
public class Run()
{
MyClass c = new Myclass();
c.varA = "Toto";
c.varB = new string[] { "foo", "bar" };
string a = c.varA.ToHtml() // -> "<p>Toto</p>";
string b = c.varB.ToHtml() // -> "<ul><li>foo</li><li>bar</li></ul>";
}
How can do that ?
Edit: I have change the Run()
Create an extension method on the String class, which returns a HTML representation of that string (or whatever ToHtml() should do).
public static class StringExtensions
{
public static string ToHtml ( this string target )
{
// TODO :
}
}
This is a way to implement your scenario with extension methods. While, as others have noted, it would make sense to keep the logic to turn your strings to HTML within MyClass, in certain scenarios it might make sense to use this approach.
public class MyClass
{
public String varA{ get; set; }
public String[] varB{ get; set; }
}
public static class MyExtensions {
public static string ToHtml(this string input, string format)
{
return string.Format(format, input);
}
public static string ToHtml(this string input)
{
return ToHtml(input,"<p>{0}</p>");
}
public static string ToHtml(this IEnumerable<string> input, string wrapperformat, string elementformat)
{
string body= input
.Select(s => string.Format(elementformat,s))
.Aggregate((a,b)=> a+b);
return string.Format(wrapperformat,body);
}
public static string ToHtml(this IEnumerable<string> input)
{
return ToHtml(input,"<ul>{0}</ul>","<li>{0}</li>");
}
}
Unless you define ToHtml() extension methods for both strings and arrays, you can't call it that way (on the fields themselves). See the other answers for how to implement extension methods.
A simpler alternative that applies to just MyClass is to make two overloads of your method which accept a string and a string array as arguments respectively, then pass them:
public string ToHtml(string arg)
{
//return HTML value
}
public string ToHtml(string[] argAsArray)
{
//return HTML value
}
Then call them like this:
string a = c.ToHtml(c.varA);
string b = c.ToHtml(c.varB);
What you're trying to do is add an helper method to the string class. It's called an extension method and it must respect certains rules :
It must use this on the first parameter
It must be static
It must be in a static class
.
public static class HtmlStringHelper
{
public static string ToHtml(this string s)
{
// Add you logic here
return (s);
}
}
i suppose you could use an extension method (for both string and string[] for that), but then you would not need the ToHtml() method of MyClass (as the logic would reside in the extension methods).
edit: i should note that calling member methods usually is considered a bad practice. Without more information its hard to imagine what MyClass is supposed to do/be, but you might want to keep control of class members in the class. So another way would be to create a ToHtmlA() and ToHtmlB() method for MyClass.
If you changed ToHtml to except a value:
public static string ToHtml(string a)
{
// your code here - obviously not returning ""
return "";
}
then you can call it like so:
MyClass c = new MyClass();
c.varA = "some text";
c.varA = MyClass.ToHtml(c.varA);
But, I maybe WAY off what you require.

How should I encapsulate this multi-dimensional enum?

In my application I've got some information that can be one of a small set of values - so I'd like to use an enum to hold it, ensuring valid values through type-safety at compile time:
public enum Something { A1, A2, A3, B1, B2, C1 };
These enums represent multi-dimensional data (they have a letter and a number in the example above), so I'd like to be able to get the value associated with them, e.g.
Something example = Something.A1;
// Now I want to be able to query the values for example:
example.Letter; // I want to get "A"
example.Number; // "1"I want to get 1
I've two possible solutions, neither of them feel very 'clean', so I was interested in which people prefer, and why, or whether anyone has any better ideas.
Option 1:
Create a struct which wraps the enum, and provides properties on the wrapped data, e.g.
public struct SomethingWrapper
{
public Something Value { get; private set; }
public SomethingWrapper(Something val)
{
Value = val;
}
public string Letter
{
get
{
// switch on Value...
}
}
public int Number
{
get
{
// switch on Value...
}
}
}
Option 2:
Leave the enum as it is and create a static Helper class which provides static functions that get the values:
public static class SomethingHelper
{
public static string Letter(Something val)
{
// switch on val parameter
}
public static int Number(Something val)
{
// switch on val parameter
}
}
Which should I choose, and why? Or is there a better solution I've not thought of?
Third option: like the second option, but with extension methods:
public static class SomethingHelper
{
public static string Letter(this Something val)
{
// switch on val parameter
}
public static int Number(this Something val)
{
// switch on val parameter
}
}
Then you can do:
Something x = ...;
string letter = x.Letter();
It's unfortunate that there aren't extension properties, but such is life.
Alternatively, create your own pseudo enum: something like this:
public sealed class Something
{
public static Something A1 = new Something("A", 1);
public static Something A2 = ...;
private Something(string letter, int number)
{
Letter = letter;
Number = number;
}
public string Letter { get; private set; }
public int Number { get; private set; }
}
Why not just use two enums, and maybe define a struct that holds one of each?

Categories