Function parameters accept everything - c#

Im quite new to C# and was wondering if it's possible to pass something to a function which is undefined / different each time, like the example below ;
string stringexam = "string"
or
int intexam = 5;
or
bool exam = false;
etc..
Myfunction(stringexam);
Myfunction(intexam);
Myfunction(exam);
public static void MyFunction(accepteverything) {
//DO SOMETHING
}
How could something like this be achieved ?
I need this because then I could use something like this in my code :
MyFunction(1,"ok example 1");
MyFunction(2, 22);
MyFunction(3, false);
Then I could continue in the MyFunction :
MyFunction(int method, accepteverything?!)
{
if(method == 1) {
ContinueExample1(string accepteverything); // CALLS FUNCTION CONTINUEEXAMPLE1 WHICH NEEDS A STRING AS PARAMETER
}
if(method == 2) {
ContinueExample2(int accepteverything); // CALLS FUNCTION CONTINUEEXAMPLE2 WHICH NEEDS A INT AS PARAMETER
}
if(method == 3) {
ContinueExample3(bool accepteverything);
}
}

You can do it with method overloads, the same named function but with different parameter types.
void MyFunction(string accepteverything)
{
ContinueExample1(accepteverything);
}
void MyFunction(int accepteverything)
{
ContinueExample2(accepteverything);
}
void MyFunction(bool accepteverything)
{
ContinueExample3(accepteverything);
}
This lets you do
string stringexam = "string"
int intexam = 5;
bool exam = false;
MyFunction(stringexam);
MyFunction(intexam);
MyFunction(exam);

You can also use Generic functions. This avoids boxing/Unboxing too
public void MyFunction<T>(int method, T acceptEverything)
{
switch(method)
{
case 1: ContinueExample1(acceptEverything as string); //String parameter
break;
case 2: ContineExample2(Convert.ToInt32(acceptEverything)); //int parameter
break;
// etc.
}
}
Call like this
MyFunction(1,stringexam);
MyFunction(2,intexam);

If the behavior of the method is the same no matter what type is passed in, you could pretty easily make the method:
public void MyFunction(int method, object acceptEverything)
{
switch(method)
{
case 1: ContinueExample1(acceptEverything as string);
break;
case 2: ContineExample2(acceptEverything as int);
break;
// etc.
}
}
Unfortunately that is going to introduce a lot of boxing and unboxing.

Sure, you could. But you probably want to rethink the way you're going about things. Wanting to reduce the code you have to write is good.
Bill Gates — 'I choose a lazy person to do a hard job. Because a lazy person will find an easy way to do it.'
But it's not always necessary, and can introduce unneeded complexity to something that otherwise is simple and self-explanatory.
Think about what's going on in your code. You have an exam which you want to do something with. Presumably you're concerned that there might be more than one way to identify a given exam for different users. But, whatever it is you want to do is probably not going to change. So, let's attack from that angle: we need to be able to identify an exam given some unknown parameter.
public Exam FindExamFromAnything(object input)
{
int examID = 0;
if (int.TryParse(input.ToString(), out examID))
{
return GetExamFromID(examID);
}
else
{
return GetExamFromName(input.ToString());
}
}
public Exam GetExamFromID(int ID)
{
// get the Exam with the right ID from a database or something
}
public Exam GetExamFromName(string examName)
{
// get the Exam with the right name from a database
}
Now you've got a method that you can pass whatever, and you'll get back the thing you were looking for. Great!
Except... two years from now somebody has a list of students that took a given exam, and tries to use your method:
List<string> students = new List<string> {"Alice","Bob"};
var exam = FindExamFromAnything(students); // nope!
Doesn't work. But how would he know? There's nothing in the signature that specifies what to use as the object. Now he's got to locate your source code, or use trial and error, to figure out how to use your API. Your documentation might explain that it only takes an int or a string, but...
Instead, it's not really that much more work to write a second method. As Scott Chamberlain points out you can overload a method name to take different parameters. A better solution for this implementation is to get more specific; I'm partial to methods like above exposed, that is, expose your GetExamFromString and GetExamFromID and whatever else you need, so they are self explanatory.

Related

A general way of accessing Lists by a method

I have a lot of lists and I need to display them and to check items of the lists too.
I don't want to create a method for each list, instead I would like to access them like void Display() and call the lists in my main method Display(name of the list)
I have a list named Family and with the method I check if the input of the user is equal or not to it. As the result of checking, the user gets points for it.
My question is, is there a way to make this method general that I can access them like the example above, so I don't need as many methods as list, instead just one?
public void Check()
{
for (int i = 0; i < 99; i++)
{
if (ListOne.Family.Contains(UserInput()))
{
Console.WriteLine("Correct!");
points++;
// Exit if max points reached
if (points == ListOne.Family.Count)
break;
}
else
Console.WriteLine("Wrong!");
}
}
The above example isn't necessarily the way to approach it, simply because of the lack of flexibility with the design. For example, if you try using generics you'll get something like this:
public void Check<T> (List<T> myList) where T : class
{
var listType = typeof(T);
switch (listType.Name)
{
case "List1":
break;
case "List2":
break;
}
}
The switch is code smell because if you have to add many lists, the switch becomes difficult to manage. Instead use the conditional to polymorphism approach and follow the strategy pattern or a simple factory pattern:
https://www.dofactory.com/net/strategy-design-pattern
https://www.dofactory.com/net/factory-method-design-pattern

C#: How do we try parse based on a condition?

Am trying to try parse based on a condition between two enums, how do we do this?
bool _isEnum1 = true;
public enum _Enum1
{
value,
Text,
Image
}
public enum _Enum2
{
TextArea,
Button,
Label
}
var _enum = _isEnum1 ? Enum.TryParse("value", out _Enum1 _enum) : Enum.TryParse("TextArea", out _Enum2 _enum)
I want '_enum' to hold right enum type value. Is this possible? Any other alternative is also fine.
Well, you're trying to have the type being dynamically resolved at runtime. You either have to split your entire program flow
if(_isEnum1)
{
Enum1 e = (Enum1)Enum.Parse(typeof(Enum1), "value");
HandleEnum1(e);
}
else
{
Enum2 e = (Enum2)Enum.Parse(typeof(Enum2), "value");
HandleEnum2(e);
}
where HandleEnumX are strongly typed with EnumX, so that the compiler knows what's going on, or go completely crazy overboard and use dynamic
dynamic e;
if(_isEnum1)
{
e = (Enum1)Enum.Parse(typeof(Enum1), s);
}
else
{
e = (Enum2)Enum.Parse(typeof(Enum2), s);
}
// Now e is either Enum1 or Enum2, resolved at runtime.
However, this seems wildly overcomplicated and more of a thought experiment than real code you should be pushing to production. You should probably rethink your design of this part of the program. At the very least, you might want to wrap your enums in a class to allow a more flexible design.
As a side note - you're using TryParse but never testing the returned value, so I took the liberty of exchanging them to Parse.
Enum result;
if (this._isEnum1)
{
result = (_Enum1)Enum.Parse(typeof(_Enum1), "value");
}
else
{
result = (_Enum2)Enum.Parse(typeof(_Enum2), "TextArea");
}

C# not passing parameters if those parameters are optional

I am hoping that this is a simple question, and it's just my brain that is missing that final link. And if there is another q&a elsewhere, please point me there and close this... but I couldn't find it anywhere.
Here is the gist:
I have a class with a method with optional parameters, something along the lines of
public class Test
{
public void Method(string required, string someoptionalparameter="sometext", string anotheroptionalparameter="someothertext")
{
// do something here with the parameters
}
}
So far, so good.
Now, I am going to instantiate the class and call the method in my code:
...
Test.Method("RequiredString");
and that will work. If I provide optional parameters, it will still work.
But how do I handle a scenario, where I do not know if an optional value is actual provided. So for instance:
...
Test.Method(requiredString,optionalString1,optionalString2);
...
What if I do not know, if the optionalString1 and optionalString2 have a value or not? Do I then need to write an override for every scenario, along the lines of...
if (optionalString1.isEmpty() && optionalString2.isEmpty())
{
Test.Method(requiredString);
}
else if ((!optionalString1.isEmpty() && optionalString2.isEmpty())
{
Test.Method(requiredString, optionalString1);
}
else if...
There has to be another way, and I bet it is simple and I am just having one of those Fridays... Is there something like...
Test.Method(requiredStrinig, if(!optionalString1.isEmpty())...
You should invert the logic - have those optional parameters be null and then do checks in method. So in your case method should be something like:
public void Method(string required, string opt1 = null, string opt2 = null)
{
opt1 = opt1 ?? "some default non-null value if you need it";
opt2 = opt2 ?? "another default value, this one for opt2";
// for those not knowing what it does ?? is basically
// if (opt1 == null) { opt1 = "value"; }
//... rest of method
}
Then calling that method will be easier in outside code and the logic within the method will be able to handle null cases. Outside of method you don't need to worry about those extra parameters, i.e. you can call the method any way you want, like:
Test.Method(requiredString);
Test.Method(requiredString, "something");
Test.Method(requiredString, null, "something else");
Also as #Setsu said in comment you could do this to avoid passing null as second parameter:
Test.Method("required", opt2: "thanks #Setsu");
Use overloads instead, it gives you better semantics and in case you guess the parameters from client code you'd be sure what overload to use, besides, you'll have all the machinery in one place, check out this technique, hope this helps, regards.
class Program {
static void Main(string[] args) {
Work("Hi!");
}
private static void Work(String p1) {
Work(p1, null, null);
}
private static void Work(String p1, String p2) {
Work(p1, p2, null);
}
private static void Work(String p1, String p2, String p3) {
if ( String.IsNullOrWhiteSpace(p2) ) p2 = String.Empty;
if ( String.IsNullOrWhiteSpace(p3) ) p3 = String.Empty;
Console.WriteLine(String.Concat(p1, p2, p3));
}
}
Optional parameters, are, well, optional. They seem to be a way to reduce the number of overloads you have for a method. If you receive all three parameters, you will have to decide if the second or third parameters are empty and need set to their "default" values.
My suggestion is you call your method with three strings and decide in the method if you have to change the values for string two and three. I would probably use a const or readonly instead of the default values.

Objects with many value checks c#

I want to see your ideas on a efficient way to check values of a newly serialized object.
Example I have an xml document I have serialized into an object, now I want to do value checks. First and most basic idea I can think of is to use nested if statments and checks each property, could be from one value checking that it has he correct url format, to checking another proprieties value that is a date but making sue it is in the correct range etc.
So my question is how would people do checks on all values in an object? Type checks are not important as this is already taken care of it is more to do with the value itself. It needs to be for quite large objects this is why I did not really want to use nested if statements.
Edit:
I want to achieve complete value validation on all properties in a given object.
I want to check the value it self not that it is null. I want to check the value for specific things if i have, an object with many properties one is of type string and named homepage.
I want to be able to check that the string in the in the correct URL format if not fail. This is just one example in the same object I could check that a date is in a given range if any are not I will return false or some form of fail.
I am using c# .net 4.
Try to use Fluent Validation, it is separation of concerns and configure validation out of your object
public class Validator<T>
{
List<Func<T,bool>> _verifiers = new List<Func<T, bool>>();
public void AddPropertyValidator(Func<T, bool> propValidator)
{
_verifiers.Add(propValidator);
}
public bool IsValid(T objectToValidate)
{
try {
return _verifiers.All(pv => pv(objectToValidate));
} catch(Exception) {
return false;
}
}
}
class ExampleObject {
public string Name {get; set;}
public int BirthYear { get;set;}
}
public static void Main(string[] args)
{
var validator = new Validator<ExampleObject>();
validator.AddPropertyValidator(o => !string.IsNullOrEmpty(o.Name));
validator.AddPropertyValidator(o => o.BirthYear > 1900 && o.BirthYear < DateTime.Now.Year );
validator.AddPropertyValidator(o => o.Name.Length > 3);
validator.Validate(new ExampleObject());
}
I suggest using Automapper with a ValueResolver. You can deserialize the XML into an object in a very elegant way using autommaper and check if the values you get are valid with a ValueResolver.
You can use a base ValueResolver that check for Nulls or invalid casts, and some CustomResolver's that check if the Values you get are correct.
It might not be exacly what you are looking for, but I think it's an elegant way to do it.
Check this out here: http://dannydouglass.com/2010/11/06/simplify-using-xml-data-with-automapper-and-linqtoxml
In functional languages, such as Haskell, your problem could be solved with the Maybe-monad:
The Maybe monad embodies the strategy of combining a chain of
computations that may each return Nothing by ending the chain early if
any step produces Nothing as output. It is useful when a computation
entails a sequence of steps that depend on one another, and in which
some steps may fail to return a value.
Replace Nothing with null, and the same thing applies for C#.
There are several ways to try and solve the problem, none of them are particularly pretty. If you want a runtime-validation that something is not null, you could use an AOP framework to inject null-checking code into your type. Otherwise you would really have to end up doing nested if checks for null, which is not only ugly, it will probably violate the Law of Demeter.
As a compromise, you could use a Maybe-monad like set of extension methods, which would allow you to query the object, and choose what to do in case one of the properties is null.
Have a look at this article by Dmitri Nesteruk: http://www.codeproject.com/Articles/109026/Chained-null-checks-and-the-Maybe-monad
Hope that helps.
I assume your question is: How do I efficiently check whether my object is valid?
If so, it does not matter that your object was just deserialized from some text source. If your question regards checking the object while deserializing to quickly stop deserializing if an error is found, that is another issue and you should update your question.
Validating an object efficiently is not often discussed when it comes to C# and administrative tools. The reason is that it is very quick no matter how you do it. It is more common to discuss how to do the checks in a manner that is easy to read and easily maintained.
Since your question is about efficiency, here are some ideas:
If you have a huge number of objects to be checked and performance is of key importance, you might want to change your objects into arrays of data so that they can be checked in a consistent manner. Example:
Instead of having MyObject[] MyObjects where MyObject has a lot of properties, break out each property and put them into an array like this:
int[] MyFirstProperties
float[] MySecondProperties
This way, the loop that traverses the list and checks the values, can be as quick as possible and you will not have many cache misses in the CPU cache, since you loop forward in the memory. Just be sure to use regular arrays or lists that are not implemented as linked lists, since that is likely to generate a lot of cache misses.
If you do not want to break up your objects into arrays of properties, it seems that top speed is not of interest but almost top speed. Then, your best bet is to keep your objects in a serial array and do:
.
bool wasOk = true;
foreach (MyObject obj in MyObjects)
{
if (obj.MyFirstProperty == someBadValue)
{
wasOk = false;
break;
}
if (obj.MySecondProperty == someOtherBadValue)
{
wasOk = false;
break;
}
}
This checks whether all your objects' properties are ok. I am not sure what your case really is but I think you get the point. Speed is already great when it comes to just checking properties of an object.
If you do string compares, make sure that you use x = y where possible, instead of using more sophisticated string compares, since x = y has a few quick opt outs, like if any of them is null, return, if the memory address is the same, the strings are equal and a few more clever things if I remember correctly. For any Java guy reading this, do not do this in Java!!! It will work sometimes but not always.
If I did not answer your question, you need to improve your question.
I'm not certain I understand the depth of your question but, wouldn't you just do somthing like this,
public SomeClass
{
private const string UrlValidatorRegex = "http://...
private const DateTime MinValidSomeDate = ...
private const DateTime MaxValidSomeDate = ...
public string SomeUrl { get; set; }
public DateTime SomeDate { get; set; }
...
private ValidationResult ValidateProperties()
{
var urlValidator = new RegEx(urlValidatorRegex);
if (!urlValidator.IsMatch(this.Someurl))
{
return new ValidationResult
{
IsValid = false,
Message = "SomeUrl format invalid."
};
}
if (this.SomeDate < MinValidSomeDate
|| this.SomeDate > MinValidSomeDate)
{
return new ValidationResult
{
IsValid = false,
Message = "SomeDate outside permitted bounds."
};
}
...
// Check other fields and properties here, return false on failure.
...
return new ValidationResult
{
IsValid = true,
};
}
...
private struct ValidationResult
{
public bool IsValid;
public string Message;
}
}
The exact valdiation code would vary depending on how you would like your class to work, no? Consider a property of a familar type,
public string SomeString { get; set; }
What are the valid values for this property. Both null and string.Empty may or may not be valid depending on the Class adorned with the property. There may be maximal length that should be allowed but, these details would vary by implementation.
If any suggested answer is more complicated than code above without offering an increase in performance or functionality, can it be more efficient?
Is your question actually, how can I check the values on an object without having to write much code?

What is the smoothest, most appealing syntax you've found for asserting parameter correctness in c#?

A common problem in any language is to assert that parameters sent in to a method meet your requirements, and if they don't, to send nice, informative error messages. This kind of code gets repeated over and over, and we often try to create helpers for it. However, in C#, it seems those helpers are forced to deal with some duplication forced upon us by the language and compiler. To show what I mean, let me present some some raw code with no helpers, followed by one possible helper. Then, I'll point out the duplication in the helper and phrase my question precisely.
First, the code without any helpers:
public void SomeMethod(string firstName, string lastName, int age)
{
if(firstName == null)
{
throw new WhateverException("The value for firstName cannot be null.");
}
if(lastName == null)
{
throw new WhateverException("The value for lastName cannot be null.");
}
// Same kind of code for age, making sure it is a reasonable range (< 150, for example).
// You get the idea
}
}
Now, the code with a reasonable attempt at a helper:
public void SomeMethod(string firstName, string lastName, int age)
{
Helper.Validate( x=> x !=null, "firstName", firstName);
Helper.Validate( x=> x!= null, "lastName", lastName);
}
The main question is this: Notice how the code has to pass the value of the parameter and the name of the parameter ("firstName" and firstName). This is so the error message can say, "Blah blah blah the value for the firstName parameter." Have you found any way to get around this using reflection or anything else? Or a way to make it less painful?
And more generally, have you found any other ways to streamline this task of validating parameters while reducing code duplication?
EDIT: I've read people talking about making use of the Parameters property, but never quite found a way around the duplication. Anyone have luck with that?
Thanks!
You should check out Code Contracts; they do pretty much exactly what you're asking. Example:
[Pure]
public static double GetDistance(Point p1, Point p2)
{
CodeContract.RequiresAlways(p1 != null);
CodeContract.RequiresAlways(p2 != null);
// ...
}
Wow, I found something really interesting here. Chris above gave a link to another Stack Overflow question. One of the answers there pointed to a blog post which describes how to get code like this:
public static void Copy<T>(T[] dst, long dstOffset, T[] src, long srcOffset, long length)
{
Validate.Begin()
.IsNotNull(dst, “dst”)
.IsNotNull(src, “src”)
.Check()
.IsPositive(length)
.IsIndexInRange(dst, dstOffset, “dstOffset”)
.IsIndexInRange(dst, dstOffset + length, “dstOffset + length”)
.IsIndexInRange(src, srcOffset, “srcOffset”)
.IsIndexInRange(src, srcOffset + length, “srcOffset + length”)
.Check();
for (int di = dstOffset; di < dstOffset + length; ++di)
dst[di] = src[di - dstOffset + srcOffset];
}
I'm not convinced it is the best answer yet, but it certainly is interesting. Here's the blog post, from Rick Brewster.
This may be somewhat helpful:
Design by contract/C# 4.0/avoiding ArgumentNullException
I tackled this exact problem a few weeks ago, after thinking that it is strange how testing libraries seem to need a million different versions of Assert to make their messages descriptive.
Here's my solution.
Brief summary - given this bit of code:
int x = 3;
string t = "hi";
Assert(() => 5*x + (2 / t.Length) < 99);
My Assert function can print out the following summary of what is passed to it:
(((5 * x) + (2 / t.Length)) < 99) == True where
{
((5 * x) + (2 / t.Length)) == 16 where
{
(5 * x) == 15 where
{
x == 3
}
(2 / t.Length) == 1 where
{
t.Length == 2 where
{
t == "hi"
}
}
}
}
So all the identifier names and values, and the structure of the expression, could be included in the exception message, without you having to restate them in quoted strings.
Alright guys, it's me again, and I found something else that is astonishing and delightful. It is yet another blog post referred to from the other SO question that Chris, above, mentioned.
This guy's approach lets you write this:
public class WebServer
{
public void BootstrapServer( int port, string rootDirectory, string serverName )
{
Guard.IsNotNull( () => rootDirectory );
Guard.IsNotNull( () => serverName );
// Bootstrap the server
}
}
Note that there is no string containing "rootDirectory" and no string containing "serverName"!! And yet his error messages can say something like "The rootDirectory parameter must not be null."
This is exactly what I wanted and more than I hoped for. Here's the link to the guy's blog post.
And the implementation is pretty simple, as follows:
public static class Guard
{
public static void IsNotNull<T>(Expression<Func<T>> expr)
{
// expression value != default of T
if (!expr.Compile()().Equals(default(T)))
return;
var param = (MemberExpression) expr.Body;
throw new ArgumentNullException(param.Member.Name);
}
}
Note that this makes use of "static reflection", so in a tight loop or something, you might want to use Rick Brewster's approach above.
As soon as I post this I'm gonna vote up Chris, and the response to the other SO question. This is some good stuff!!!
Using my library The Helper Trinity:
public void SomeMethod(string firstName, string lastName, int age)
{
firstName.AssertNotNull("firstName");
lastName.AssertNotNull("lastName");
...
}
Also supports asserting that enumeration parameters are correct, collections and their contents are non-null, string parameters are non-empty etcetera. See the user documentation here for detailed examples.
Here's my answer to the problem. I call it "Guard Claws". It uses the IL parser from the Lokad Shared Libs but has a more straightforward approach to stating the actual guard clauses:
string test = null;
Claws.NotNull(() => test);
You can see more examples of it's usage in the specs.
Since it uses real lambdas as input and uses the IL Parser only to generate the exception in the case of a violation it should perform better on the "happy path" than the Expression based designs elsewhere in these answers.
The links are not working, here is the URL:
http://github.com/littlebits/guard_claws/
The Lokad Shared Libraries also have an IL parsing based implementation of this which avoids having to duplicate the parameter name in a string.
For example:
Enforce.Arguments(() => controller, () => viewManager,() => workspace);
Will throw an exception with the appropriate parameter name if any of the listed arguments is null. It also has a really neat policy based rules implementation.
e.g.
Enforce.Argument(() => username, StringIs.Limited(3, 64), StringIs.ValidEmail);
My preference would be to just evaluate the condition and pass the result rather than passing an expression to be evaluated and the parameter on which to evaluate it. Also, I prefer to have the ability to customize the entire message. Note that these are simply preferences -- I'm not saying that your sample is wrong -- but there are some cases where this is very useful.
Helper.Validate( firstName != null || !string.IsNullOrEmpty(directoryID),
"The value for firstName cannot be null if a directory ID is not supplied." );
Don't know if this technique transfers from C/C++ to C#, but I've done this with macros:
#define CHECK_NULL(x) { (x) != NULL || \
fprintf(stderr, "The value of %s in %s, line %d is null.\n", \
#x, __FILENAME__, __LINE__); }
In this case, rather than use your own exception type, or really general types like ApplicationException.. I think it is best to use the built in exception types that are specifically intended for this use:
Among those.. System.ArgumentException, System.ArgumentNullException...
Postsharp or some other AOP framework.
It does not apply everywhere, but it might help in many cases:
I suppose that "SomeMethod" is carrying out some behavioral operation on the data "last name", "first name" and "age". Evaluate your current code design. If the three pieces of data are crying for a class, put them into a class. In that class you can also put your checks. This would free "SomeMethod" from input checking.
The end result would be something like this:
public void SomeMethod(Person person)
{
person.CheckInvariants();
// code here ...
}
The call would be something like this (if you use .NET 3.5):
SomeMethod(new Person { FirstName = "Joe", LastName = "White", Age = 12 });
under the assumption that the class would look like this:
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
public void CheckInvariants()
{
assertNotNull(FirstName, "first name");
assertNotNull(LastName, "last name");
}
// here are your checks ...
private void assertNotNull(string input, string hint)
{
if (input == null)
{
string message = string.Format("The given {0} is null.", hint);
throw new ApplicationException(message);
}
}
Instead of the syntactic sugar of .NET 3.5 you can also use constructor arguments to create a Person object.
Just as a contrast, this post by Miško Hevery on the Google Testing Blog argues that this kind of parameter checking might not always be a good thing. The resulting debate in the comments also raises some interesting points.

Categories