new keyword with -1 in C# [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 7 years ago.
Improve this question
This is the first time I saw this kind of declaration. I haven't find much information in Google. In one of the existing WPF Applications, where user try to create a new Window he instantiates the class like below. What "-1" means ? What exactly it do ?
ProductViewModel viewModel = new ProductViewModel(-1);

It's just a parameter for the constructor... When you create a class, you can specify zero (default empty constructor is created for you if you don't create at least one) or more constructors. In the constructor you usually set the variables for the class to work with. -1 usually means that the value isn't set (like a default value), but I believe in that scenario it would be better to create a constructor with an optional parameter like this:
public class ProductViewModel
{
// this is our modified constructor
public ProductViewModel(int productId = -1)
{
// do something with the values, probably set some internal field
}
}
A constructor is called always when you create an instance of a class using new keyword.
Based on the comment, the constructor had parameters declared like this:
params object[] args. It's just a fancy syntax for saying I take variable number of parameters. You can learn more about params here on C# reference: Params keyword

The depends on the code existing in ProductViewModel. I think this -1 indicates that the programmer intended to create a new Product. This -1 shall be the ProductId. If there is an Id that is greather than 0 then the details to the product will be loaded. If the Id is -1 then a new production should be created.
Thats is my idea about what this constructor parameter will do.

Related

two differents method or additional parameter? [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 have a method set in an POCO entity that set the basic property and the navigation property. In some cases, I don't need to verify some conditions, but in another cases I need to verify to ensure that the information is coherent in the database, but this verification makes me to get extra data from database.
So by the moment I have my basic method that is this:
public void setMyProperty(MyType paramProperty)
{
this.Property = paramProperty;
this.IDProperty = paramProperty.IDPorperty;
paramProperty.MyNavigationCollection.Add(this);
}
For the method that verifies the data, I guess that I have two options.
First one, I can create a new method for business logic, somthing like that:
public void setPropertyBi(MyType paramProperty)
{
//check conditons
//If all OK then
this.setPorperty(paramProperty);
}
But I have another option, use only one method, not the basic method and the other for business checks. Something like that:
public void setProperty(MyType paramType, bool paramDoChecks)
{
if(paramDoChecks)
{
//Do checks
}
//if all OK
this.Property = paramProperty;
this.IDProperty = paramProperty.IDPorperty;
paramProperty.MyNavigationCollection.Add(this);
}
Which is the recommended option? or there are another ways?
People here seem to prefer the flag, I personally think it is horrible.
You want to achieve two different things: just set a property; validate AND set a property. IMHO it should be two separated methods.
Just don´t write two different Methods if it´s one equaly functionality. Just add a Parameter which makes the validation-difference like you´ve written last.
But don´t forget to enter the behaviour if validation failed. separate it well.
You could add a Boolean ValidationRequiredproperty to MyType which you can set before the call to setMyProperty().
I prefer to have two methods: CanSetProperty and SetProperty.
CanSetProperty: just check the condition, does not change anything in the parameter.
SetProperty: will modify the paramenter.
I think this code is a good candidate to follow the Command Query Separation Pattern
The fundamental idea is that we should divide an object's methods into
two sharply separated categories:
Queries: Return a result and do not change the observable state of the
system (are free of side effects).
Commands: Change the state of a
system but do not return a value.

Do I always have to use constructor in C# [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Do I always have to use constructor in C#?
I am working on some examples. They use constructor. I am not sure if I understand it, because I feel that I don't have to use constructor.
If a constructor isn't defined, a default constructor is automatically generated for you. The generated code is the same as writing:
public MyClass() : base()
{
}
If you want parameters, or member initialization, then you will need to write your own. You also need to write one if you inherit from a a base class with parameters. Since you are just learning about constructors, you don't need to worry about it yet, but it is something to keep in mind.
Note that this constructor is removed if you define any constructor (even a parameterized one), so you need to explicitly define it if you still want a parameterless one.
Here is the documentation of a default constructor: MSDN
A default constructor is created for every class. However you can create your own constructor with or without parameteres.
You should use Constructors when your class for example needs to manipulate an object that it requires.
For example:
public class Car
{
string _model = "";
public Car(string CarModel)
{
this._model = CarModel;
}
}
Not to be rude but you have to give it a try.
A class does not need a constructor (or at least will generate one calling the base classes' matching constructor, if one) unless:
You want to do some initialisation of variables;
You want to pass in parameters;
You need to since the base class doesn't have a parameterless constructor.
The purpose of constructor is that if you have some code to execute when the object is created, write it in constructor. EDIT Using constructor is not obligatory in C#. For the classes which you create through a wizard, a constructor you will see created by default. But for the class which you create/write, you may create/write constructor.

Is reassigning parameter (locally) inappropriate? [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 9 years ago.
Improve this question
Is there a broad aversion in the C# community to modifying parameters? For example, would a popular style-checker complain about the parameter reassignment aspect of the following?
public void Create(Template template = null) {
if (template == null) template = GetDefaultTemplate();
// ...
}
An alternative to this would be the following, but assuming code blocks are appropriately small, it's probably not any clearer:
public void Create(Template template = null) {
var theActualTemplate = template ?? GetDefaultTemplate();
// ...
}
I apologize for this surely tired/already-answered question, but oddly I can't find anything on it. I tried looking through some C# style guides (including all the ones here: Style guide for c#?), but didn't find this issue covered. Maybe it's a non-issue?
If you have a relatively authoritative source for this, I'd love to hear it.
In your sample you are just modifying the variable inside your method scope. Since that is your local variable, your method can do with it whatever it wants - it does not impact the caller. In general it is better to use the same variable because it makes the code easier to maintain - if you create a new variable, you increase the risk of accidentally using the wrong one and get NullReferenceException.
If you would be using ref keyword only then the assignment will impact the caller.
It can be useful when you need to set a default value for a reference type, because you can't really specify it like you would do for a value type.
public void Create(int templateId = 1) {
// this will compile
// ...
}
public void Create(Template template = GetDefaultTemplate()) {
// this WON'T compile
// ...
}
Using null as a default value for a reference type can help you defining a default object for your parameter.

Is there any sense in such kind of refactoring? [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
Given web service method:
public void FindSomeEntities(int? Id, string param1, int? param2, ...)
Refactored:
public void FindSomeEntities(SelectionParameters selectionParameters)
class SelectionParameters
{
public int? Id;
public string param1;
public int? param2
...
}
Pros:
too many parameters in original web service method reduced to the
only one
if there is need to change we won't have to change the
interface of the method - only the definition of SelectionParameters
Cons:
class SelectionParameters hasn't any business value - it's used only
as helper class and it's used in a single method. As a result we'll
have many methods with 1 parameters and plenty of one-off classes
Actually the interface IS changed, we just push these changes a bit
deeper.
This refactoring is called Introduce Parameter Object. It is likely to be a good idea if the parameters are naturally related to each other, and especially if they're frequently used together as parameter lists to multiple methods.
I'm not sure there is much value in this kind of refactoring because as you say, the number of supporting classes will/could be a pain to maintain and serve no other purpose.
If the parameters have distinct purposes, such as in your example 'ID' then I would think it would be sensible to keep them separate so as to make it easy to identify them and what you want to do with them in the method body.
If however your params are just a collection of values which perform similar/the same functions in the method body, you could look at using the params keyword and defining your method like this:
public void FindSomeEnteties(params object[] theParameters)
It depends whether you want to have to dig through an array to pull out index 0 and treat it as the ID, etc etc, or whether your method simply wants to do the same thing to all the parameters passed.
If there is any reason to believe that the same (sub)set of parameters is shared by other web services, this is reasonable.
Whether you do it not, you have a defacto struct as the argument list anyway. This observation is realized in our PARLANSE programming language, which has always a single argument to function, named '?' (sort of like "self" in OO ). That argument has a type; it can be a scalar or complex variable (int or string), or it can be struct. Normally one defines a struct by a struct declaration; in PARLANSE, writing what appears to be multiple arguments implicitly defines a struct. In those cases where the argument list is passed to a child function, one can simply call that child function on '?' and the entire argument list is passed.

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