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

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.

Related

Why creating Constructor when Default can do the all? [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 1 year ago.
Improve this question
Hope you are fine. I started learning C# about 2 weeks ago.I’ve been watching videos since now. Now he is teaching Constructions . I don’t get it. When you can use all strings and all numerical values, why restricting them? I mean does it make things bad if you just let it to be default? I tried many ways but I couldn’t find my proper answer. Your reply is so much to me and I really like to know why?!
There are many reasons why one might want to use a constructor, but they are optional and depend on what the developer wants to do.
Constructors can receive parameters and set values based on the
passed values/objects. So you can have many different constructors setting up the object in different ways
Constructors can also include logic to determine how fields/properties should be set. If at all
Constructors can call other constructors of the same class
Constructors are needed if you are using dependency injection, or
readonly fields/properties.
If you want to create copies of your class object, then constructors
can be very useful way to do this. Especially deep copies.
You can also have a static constructor. It is invoked only once in
the class and it is invoked during the creation of the first
reference to a static member in the class.
Constructors can also be private. And you can have a mix of public
and private constructors.
Constructors are useful in inheritance, to ensure that parent
fields/properties are still set correctly no matter what the child does (the child can then change these of course
Sometimes it is as simple as if you are setting many default values,
it can be easier to read if they are all in the same place where you can group them together can comment on them together
BTW: Even if you don't create a constructor, the compiler will create a default one for you.
So simply put, C# provides you with lots of different options. It is up to you to select the one which suits you best for this specific task & class.
There are several topics you can explore that will show where it is necessary...
Dependency injection and Private Readonly Properties for example.
It can also just be convenient
new Uri(pathNameString) will generate the Uri object you can put in an http request by just providing the string at instantiation.

ASP.NET Core - Any reason not to use a parameter object with dependency injection? [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
I like the DI feature of ASP.NET Core, but am finding that some of my classes end up with huge constructor parameter signatures...
public class Foo {
private IBar1 _bar1;
private IBar2 _bar2;
// lots more here...
public Foo(IBar1 bar1, IBar2 bar2, lots more here...) {
_Bar1 = bar1;
_Bar2 = bar2;
// ...
}
public DoSomething() {
// Use _bar1
}
}
In case this looks like a code smell, it's worth pointing out that any controller is going to use AutoMapper, an email service and 2 or 3 managers related to ASP.NET Identity, so I have 4 or 5 dependencies before I start injecting a single repository. Even if I only use 2 repositories, I can end up with 6 or 7 dependencies without actually violating any SOLID principles.
I was wondering about using a parameter object instead. I could create a class that has a public property for every injected dependency in my application, takes a constructor parameter for each one, and then just inject this into each class instead of all the individual Bars...
public class Foo {
private IAllBars _allBars;
public Foo(IAllBars allBars) {
_allBars = allBars;
}
public DoSomething() {
// Use _allBars.Bar1
}
}
The only disadvantage I can see is that it would mean that every class would have every dependency injected into it via the parameter object. In theory, this sounds like a bad idea, but I can't find any evidence that it would cause any problems.
Anyone any comments? Am I letting myself into potential trouble by trying to make my constructor code neater?
What you're describing sounds like the service locator pattern, and while it seems tempting to simplify your code by eliminating all those constructor parameters, it usually ends up hurting maintainability in the long run. Check out Mark Seemann's post Service Locator violates encapsulation for more details about why it should be avoided.
Generally, when you find yourself with a class with dozens of constructor parameters, it means that class might have too many responsibilities. Can it be decomposed into a number of smaller classes with narrower goals? Rather than introducing a "catch-all" class that knows about everything, maybe there's a complex part of your application that you can abstract behind a facade.
Sometimes, you do end up with large coordinator classes that have many dependencies and that's okay in certain circumstances. However, if you have many of these it's usually a design smell.

Calling a class in another way [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I am just a beginner and I am trying to learn other alternatives.
Is there another way to call a class from another class. For example, I have a class called Test, can you call it in another way from this one = Test example = new Test();
You can have a Type Factory class which can create an instance for you dynamically. Read some articles about type factory.
Its a very common way to dynamically create instances of a type.
Lets say you have a program that generates text files. As parameter you can ask for a specific template, the program should then browse through your classes of type text generator and create an instance matching your requested template.
If you need to create an instance of this class i.e this is not a static class then
Test example = new Test();
is the correct way to call this class.
If this was a static class e.g public static Test {... then you could call this class without creating a new instance of it e.g Test.SomeMethod Example Link

class.forName equivalent in c# without creating an instance [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 5 years ago.
Improve this question
I want to dynamically access classes in c# in the way like Java class.forName(). I have only found things like Class.forName() equivalent in .NET? but I don't want to create instances.
In detail: I have got a simple text file containing a list of classes. I read them using file.ReadLine() (so I have got all class names as strings) and then I want to execute the same static method on each class: class1.method(); class2.method; and so on. The classes all exist and I need to access them. How can I do that?
C# doesn't support static interfaces (or static members in interfaces), so unless you want to use factory classes (the usual approach), you'll need to use reflection to invoke the static method directly.
void Main()
{
Console.WriteLine(Type.GetType("A").GetMethod("Hi").Invoke(null, new object[] {}));
}
class A
{
public static string Hi() { return "Hi!"; }
}
You might want to use a fully-qualified name for the type to make this work really well. Using just the name of the type is tricky, especially when you're trying to invoke types from other assemblies (which you probably are, otherwise there'd be no reason to use reflection - just use a dictionary of delegates or whatever).
You can use System.Reflection to load the Assembly into memory and then drill down to the type followed by getting the required method and invoke.
Refer to the documentation
GetMethod
If you have names of your desired Type then you can use Type.GetType(string) method.
Example if you have a class like this :
namespace MeProgram.BusinessLogic
{
public class MeObject {}
}
Full class name of that object should be "MeProgram.BusinessLogic.MeObject".
Now you can use that name inside of Type.GetType(string) method like such :
string className = "MeProgram.BusinessLogic.MeObject";
Type classType = Type.GetType(className);

new keyword with -1 in C# [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 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.

Categories