Generic methode vs cast [closed] - c#

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
I have a methode searching for a winform control by name. My first approche was to do it like that
private Control SearchControlByName(Control parent, string name){recursive search...}
Calling the methode looks like
Label temp = (Label)SearchControlByName(panel1, "label4");
Then a thought to myself it would be better do do it with an generic methode like this
private T SearchControlByName<T>(Control parent, string name) where T : Control {recursive search}
calling like
Label temp = SearchControlByName<Label>(panel1, "label4");
And now I'm not sure which is the better approach. What are the advantages / drawbacks of the generic method vs casting after calling the method?
In the generic methode I also have to cast the result like this
return (T)result

I don't think there are any disadvantages.
Since there are at least two advantages (see below), I would use the generic version.
It's prettier (no need for that cast).
You could use OfType<T> on Control.Controls inside the implementation (your recursive search) so you don't have to worry about returning a Label when the person wants a PictureBox. However keep in mind that you can only do that at the bottom level, otherwise you won't go through all the elements of course.

Related

Use a single dictionary object instead of multiple method parameters (similar to args[] in Main method) [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
Can a single dictionary object be used in place to replace method parameters (similar to args in Main method) is this a good idea or if bad? what would be a better approach than this?
private async Task<OperationResult> AddOrUpdateRecord(Dictionary<string, object> args)
{
args.TryGetValue("record", out object record);
...
... etc
var recordExists = new RecordExists(record as RecordDto, _dnsCommonActionsRepo);
}
is this a good idea or if bad
This is in the vast majority of cases a very bad idea. The caller will have no idea what parameters are needed. You cannot pass any typed object, so you lose all type safety. You will have no compiler checks to catch potential errors. You are also likely to reduce performance if that is a concern.
what would be a better approach than this?
In most cases, regular parameters. In some cases, where you have way to many parameters, and is unable to refactor the method, a parameter object that gathers many different parameters might be motivated. The only use case I can think of for something like this is when you are getting untyped parameters from some source, for example, key-value pairs from a database or file.
If the problem is breaking builds due to signature changed, that is intentional. The compiler saves you from shooting yourself in the foot. Good refactoring tools, like R# allows modification of signatures, but if you add a parameter, chances are you need to fix call sites by hand.

Is using C#'s Type (Reflection) bad practice? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
edit Hmm, I don't believe this is a duplicate of other questions asking about var. I am asking about Reflection, and just curious if it should be used sparingly like var
Also an extra shout out to Flydog57 for their responses in comments, I appreciate them~ edit
Forgive me if my question is improper, first time posting my own. I am trying to be more proper with my code while also trying to get things I've never tried before to work~
Playing around with code seeing what I can and can't do. Even if it has no real point or purpose. Just using it as a way to entertain myself and learn as I go.
My current project is having one script add more lines of code to a different file. I thought about this when I realized that code is just text, and you can make code that adds text to a file.
So I was thinking of code that would write new methods that can be called. For this to work, I'd have to be able to call a method by a string name however. So I researched if I can do something like that. And this is what I found:
Type thisType = this.GetType();
MethodInfo theMethod = thisType.GetMethod(TheCommandString);
theMethod.Invoke(this, userParameters);
ottobar's response here
I know that certain langues are not SUPPOSED to do certain things.
Like C# can use var or dynamic, but it is best to avoid them as much as possible.
My understanding is this is because C# (unlike things like Python) like to work with "knowns", and doesn't like "unknowns"
Too Long Didn't Read:
Is Type thisType = this.GetType(); something I should only use in very specific situations like var and dynamic?
You should only use that (...MethodInfo theMethod = thisType.GetMethod(TheCommandString)
when you don't have access to the method (TheCommandString) or the class , so it mostly can be used in building something like DI , or in libraries like newtonsoft or automapper.
so in your example if you have access to your method (TheCommandString) you should directly call that ( object.TheCommandString(userParameters)) , if you don't have access (eg : its a private method inside a dll) then you can use reflection.

Should we declare a collection class or interface? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
I've got this idea from Java - i was told that you should declare a collection like this
List<Object> myList = new ArrayList<Object>();
where ArrayList is a class implementing List interface. The point of this is to enhance maintainability by generalizing code - as, should you change teh implementation to, e.g LinkedList<Object>, you could to it 100% painlessly.
So, projecting this on C#, is it considered a good practice to do the same thing in C# :
IList<Object> list = new List<Object>()
?
EDIT : i just found that LinkedList in C# does not even implement the IList interface, so i guess it settles the question for lists at least
Yes, generally this is a good practice to use interfaces wherever you can.
There are two important exceptions for containers, though:
When you must use a hash-based container for objects that are not comparable, use HashSet<T> or Dictionary<TK,TV>,
When you declare a local variable, using var for implicit typing is often preferred for convenience,
Note that if you plan to use a sorted container you have IOrderedSet<T> and IOrderedDictionary<TK,TV>.

what is best way to prepare C# objects in separate methods [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
What is better method to use for object preparation logic:
a) with return value
List<Users> users = LoadUsers();
users = PrepareUsers(users);
b) or with void type
List<Users> users = LoadUsers();
PrepareUsers(users)
Are you setting properties on existing User objects or are you creating new ones?
If you're simply changing existing objects, then there's no reason why you'd want to return them, it's redundant. Worse, it's misleading - the client will think his objects were left untouched and that you're creating new objects when in fact you're not.
If you're creating new ones, well then, you obviously need to return them.
Alternative b. since you are working with the same user objects, there is no reason to reassign the variable.

Parse method or overload the constructor [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
When writing a method that takes a string and populates a poco based on it, is it better to have a static Parse(string s) method like Int32.Parse() or overload the constructor so it takes a string?
I prefer the constructor version, but including both is easy, since the constructor can just call Parse. This is the pattern followed by the Guid struct (and likely others as well.)
I should add that if you're not dealing with a struct, then the static method should probably be referring to the constructor (or even a separate method that both can call) since you can't assign to this in a class constructor.
EDIT: As TrueWill points out, if you do include Parse, you should include TryParse as well. Incidentally, Guid is once again instructive: the Parse method actually uses TryParse, and just throws an exception if TryParse returns false.
If the method might fail due to an invalid string, I'd lean towards Parse and include TryParse as per the TryParse pattern.
I would recommend using .Parse(string s) if its a simple object, if the object stores more then 1-2 values you should use the constructor, or in other words, dont parse if the return value will be an instance with memebers unaffected by the parse value.

Categories