How to store all ctor parameters in fieldsHow do I calculate someone's age in C#?Hidden Features of C#?How do...
How do I add a strong "onion flavor" to the biryani (in restaurant style)?
In the Lost in Space intro why was Dr. Smith actor listed as a special guest star?
Integral problem. Unsure of the approach.
How can I differentiate duration vs starting time
How can changes in personality/values of a person who turned into a vampire be explained?
Identical projects by students at two different colleges: still plagiarism?
Can I do anything else with aspersions other than cast them?
How Create a list of the first 10,000 digits of Pi and sum it?
Why does this quiz question say that protons and electrons do not combine to form neutrons?
Why write a book when there's a movie in my head?
Why would you use 2 alternate layout buttons instead of 1, when only one can be selected at once
How bad is a Computer Science course that doesn't teach Design Patterns?
Sets which are both Sum-free and Product-free.
How do I write a maintainable, fast, compile-time bit-mask in C++?
Including proofs of known theorems in master's thesis
Buying a "Used" Router
Can you wish for more wishes from an Efreeti bound to service via an Efreeti Bottle?
Do the speed limit reductions due to pollution also apply to electric cars in France?
What does "don't have a baby" imply or mean in this sentence?
Is it common to refer to someone as "Prof. Dr. [LastName]"?
Build ASCII Podiums
How does holding onto an active but un-used credit card affect your ability to get a loan?
Is layered encryption more secure than long passwords?
Have the UK Conservatives lost the working majority and if so, what does this mean?
How to store all ctor parameters in fields
How do I calculate someone's age in C#?Hidden Features of C#?How do I enumerate an enum in C#?What is the difference between a field and a property?How do I get a consistent byte representation of strings in C# without manually specifying an encoding?How to loop through all enum values in C#?How do I generate a random int number in C#?What is a NullReferenceException, and how do I fix it?How to avoid “too many parameters” problem in API design?Evaluate equality among n variables, without check each pair
I'm learning C# and a thought came up when coding. Is it possible to automaticly store parameters from a constructor to the fields in a simple way without having to write this.var = var
on every variable to store them?
Example:
class MyClass
{
int var1;
int var2;
int var3;
int var4;
public MyClass(int var1, int var2, int var3, int var4){
this.var1 = var1;
this.var2 = var2;
this.var3 = var3;
this.var4 = var4;
}
}
Is there a way to avoid writing this.varX = varX
and save all the variables to the fields if the names are the same?
c# oop
New contributor
|
show 1 more comment
I'm learning C# and a thought came up when coding. Is it possible to automaticly store parameters from a constructor to the fields in a simple way without having to write this.var = var
on every variable to store them?
Example:
class MyClass
{
int var1;
int var2;
int var3;
int var4;
public MyClass(int var1, int var2, int var3, int var4){
this.var1 = var1;
this.var2 = var2;
this.var3 = var3;
this.var4 = var4;
}
}
Is there a way to avoid writing this.varX = varX
and save all the variables to the fields if the names are the same?
c# oop
New contributor
2
As of my knowledge no! :(
– abhinavxeon
1 hour ago
No. but fields and arguments should have similar yet different names - for instance, having fields always begin with an underscore is one fairly common way to distinguish them from anything else. You would still need to explicitly set the fields in the constructor, but you wouldn't have to use thethis
keyword for it: (i.e_var1 = var1
)
– Zohar Peled
1 hour ago
1
No, but just to speed things up you do something like this (in VS): docs.microsoft.com/en-us/visualstudio/ide/reference/…
– Nanna
1 hour ago
1
Write the parameter (e.g.int var1
). Selectvar1
and pressControl .
. Options will appear to write the assignment code for you.
– mjwills
1 hour ago
Of course no. I mean, you can use Properties instead or use quick actions and refactoring, but to make it automatically assign your fields, because you are tired to write same thing over and over, no.
– SeM
1 hour ago
|
show 1 more comment
I'm learning C# and a thought came up when coding. Is it possible to automaticly store parameters from a constructor to the fields in a simple way without having to write this.var = var
on every variable to store them?
Example:
class MyClass
{
int var1;
int var2;
int var3;
int var4;
public MyClass(int var1, int var2, int var3, int var4){
this.var1 = var1;
this.var2 = var2;
this.var3 = var3;
this.var4 = var4;
}
}
Is there a way to avoid writing this.varX = varX
and save all the variables to the fields if the names are the same?
c# oop
New contributor
I'm learning C# and a thought came up when coding. Is it possible to automaticly store parameters from a constructor to the fields in a simple way without having to write this.var = var
on every variable to store them?
Example:
class MyClass
{
int var1;
int var2;
int var3;
int var4;
public MyClass(int var1, int var2, int var3, int var4){
this.var1 = var1;
this.var2 = var2;
this.var3 = var3;
this.var4 = var4;
}
}
Is there a way to avoid writing this.varX = varX
and save all the variables to the fields if the names are the same?
c# oop
c# oop
New contributor
New contributor
edited 1 hour ago
croxy
2,83061938
2,83061938
New contributor
asked 1 hour ago
Fredrik PerssonFredrik Persson
342
342
New contributor
New contributor
2
As of my knowledge no! :(
– abhinavxeon
1 hour ago
No. but fields and arguments should have similar yet different names - for instance, having fields always begin with an underscore is one fairly common way to distinguish them from anything else. You would still need to explicitly set the fields in the constructor, but you wouldn't have to use thethis
keyword for it: (i.e_var1 = var1
)
– Zohar Peled
1 hour ago
1
No, but just to speed things up you do something like this (in VS): docs.microsoft.com/en-us/visualstudio/ide/reference/…
– Nanna
1 hour ago
1
Write the parameter (e.g.int var1
). Selectvar1
and pressControl .
. Options will appear to write the assignment code for you.
– mjwills
1 hour ago
Of course no. I mean, you can use Properties instead or use quick actions and refactoring, but to make it automatically assign your fields, because you are tired to write same thing over and over, no.
– SeM
1 hour ago
|
show 1 more comment
2
As of my knowledge no! :(
– abhinavxeon
1 hour ago
No. but fields and arguments should have similar yet different names - for instance, having fields always begin with an underscore is one fairly common way to distinguish them from anything else. You would still need to explicitly set the fields in the constructor, but you wouldn't have to use thethis
keyword for it: (i.e_var1 = var1
)
– Zohar Peled
1 hour ago
1
No, but just to speed things up you do something like this (in VS): docs.microsoft.com/en-us/visualstudio/ide/reference/…
– Nanna
1 hour ago
1
Write the parameter (e.g.int var1
). Selectvar1
and pressControl .
. Options will appear to write the assignment code for you.
– mjwills
1 hour ago
Of course no. I mean, you can use Properties instead or use quick actions and refactoring, but to make it automatically assign your fields, because you are tired to write same thing over and over, no.
– SeM
1 hour ago
2
2
As of my knowledge no! :(
– abhinavxeon
1 hour ago
As of my knowledge no! :(
– abhinavxeon
1 hour ago
No. but fields and arguments should have similar yet different names - for instance, having fields always begin with an underscore is one fairly common way to distinguish them from anything else. You would still need to explicitly set the fields in the constructor, but you wouldn't have to use the
this
keyword for it: (i.e _var1 = var1
)– Zohar Peled
1 hour ago
No. but fields and arguments should have similar yet different names - for instance, having fields always begin with an underscore is one fairly common way to distinguish them from anything else. You would still need to explicitly set the fields in the constructor, but you wouldn't have to use the
this
keyword for it: (i.e _var1 = var1
)– Zohar Peled
1 hour ago
1
1
No, but just to speed things up you do something like this (in VS): docs.microsoft.com/en-us/visualstudio/ide/reference/…
– Nanna
1 hour ago
No, but just to speed things up you do something like this (in VS): docs.microsoft.com/en-us/visualstudio/ide/reference/…
– Nanna
1 hour ago
1
1
Write the parameter (e.g.
int var1
). Select var1
and press Control .
. Options will appear to write the assignment code for you.– mjwills
1 hour ago
Write the parameter (e.g.
int var1
). Select var1
and press Control .
. Options will appear to write the assignment code for you.– mjwills
1 hour ago
Of course no. I mean, you can use Properties instead or use quick actions and refactoring, but to make it automatically assign your fields, because you are tired to write same thing over and over, no.
– SeM
1 hour ago
Of course no. I mean, you can use Properties instead or use quick actions and refactoring, but to make it automatically assign your fields, because you are tired to write same thing over and over, no.
– SeM
1 hour ago
|
show 1 more comment
5 Answers
5
active
oldest
votes
No, there is no way to do this more easily in the current version of C#. There was a new feature in the C# 6.0 prereleases called Primary Constructors to solve this, but it was removed before the final release. https://www.c-sharpcorner.com/UploadFile/7ca517/primary-constructor-is-removed-from-C-Sharp-6-0/
Currently, I believe the C# team are working on adding records to the language: https://github.com/dotnet/roslyn/blob/features/records/docs/features/records.md - this should make working with simple data classes much simpler, as in F#
add a comment |
If you define your variables first, you can use visual studios' "Quick actions" tool to generate a constructor for you; this gives you a choice of the currently-defined class fields to include.
using this will insert a constructor class with all your selected fields as parameters, and it will assign the values to the fields.
This will not reduce the amount of code, but it will cut back on the amount of typing you need
add a comment |
The answer to your question is no, but you could use properties to get a similar fix:
class MyClass
{
public int Var1 {get;set;}
public int Var2 {get;set;}
public int Var3 {get;set;}
public int Var4 {get;set;}
public MyClass(){
}
}
void Main()
{
var myClass = new MyClass
{
Var1 = 1,
Var2 = 2,
Var3 = 3,
};
}
5
Per .NET coding convention, properties have first letter upper-case
– Teejay
1 hour ago
5
Object initializers are nice, but if you have some properties that must be initialized when creating an instance they are not a substitute replacement for constructor arguments.
– Zohar Peled
1 hour ago
1
I dont see any difference here. The initialisation was centralised in the constructor , now every time you want to accomplish that logic you'll use this object initialiser syntax. This does not answer the question.
– Zack ISSOIR
1 hour ago
add a comment |
Short: No, Long: Yes, there is a hack.
You can use a mix of reflection and storing the parameter in a temporary array to achieve that.
class TestClass
{
public string var1 { get; set; }
public string var2 { get; set; }
public string var3 { get; set; }
public TestClass(string var1, string var2, string var3) : base()
{
var param = new { var1, var2, var3 };
PropertyInfo[] info = this.GetType().GetProperties();
foreach (PropertyInfo infos in info) {
foreach (PropertyInfo paramInfo in param.GetType().GetProperties()) {
if (infos.Name == paramInfo.Name) {
infos.SetValue(this, paramInfo.GetValue(param, null));
}
}
}
}
}
This basically loops through the properties and check's whether the name equals the parameter name, which have been stored in a temporary array (you can't get the parameter value with reflection), and assigns it if they match.
Note: I do not recommend assigning properties like that, but for the sake of proof that it's possible I came up with this.
New contributor
add a comment |
In simple terms not you cant. The use of this is not necessary, but it is elegant to do and shows intent as to reinforce the fact that a variable is part of the context of a class.
However the problem here arise from the fact that both your parameters and instance variables have the same names.
The compiler is unable to differentiate between same name variables(it night complaints of circular reference).
The use of this
keyword allow us we tell the compiler that we are referring to the current instance of that variable.
I think that you can improve the code and coding per se with a better Naming approch for your variables.
Eg var1 var2 var3
they don't really say anything and make the code hard to understand.
Try to be specific and verbose :
Eg firstName, lastName, address and so forth. They are self-explanatory.
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Fredrik Persson is a new contributor. Be nice, and check out our Code of Conduct.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54824786%2fhow-to-store-all-ctor-parameters-in-fields%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
5 Answers
5
active
oldest
votes
5 Answers
5
active
oldest
votes
active
oldest
votes
active
oldest
votes
No, there is no way to do this more easily in the current version of C#. There was a new feature in the C# 6.0 prereleases called Primary Constructors to solve this, but it was removed before the final release. https://www.c-sharpcorner.com/UploadFile/7ca517/primary-constructor-is-removed-from-C-Sharp-6-0/
Currently, I believe the C# team are working on adding records to the language: https://github.com/dotnet/roslyn/blob/features/records/docs/features/records.md - this should make working with simple data classes much simpler, as in F#
add a comment |
No, there is no way to do this more easily in the current version of C#. There was a new feature in the C# 6.0 prereleases called Primary Constructors to solve this, but it was removed before the final release. https://www.c-sharpcorner.com/UploadFile/7ca517/primary-constructor-is-removed-from-C-Sharp-6-0/
Currently, I believe the C# team are working on adding records to the language: https://github.com/dotnet/roslyn/blob/features/records/docs/features/records.md - this should make working with simple data classes much simpler, as in F#
add a comment |
No, there is no way to do this more easily in the current version of C#. There was a new feature in the C# 6.0 prereleases called Primary Constructors to solve this, but it was removed before the final release. https://www.c-sharpcorner.com/UploadFile/7ca517/primary-constructor-is-removed-from-C-Sharp-6-0/
Currently, I believe the C# team are working on adding records to the language: https://github.com/dotnet/roslyn/blob/features/records/docs/features/records.md - this should make working with simple data classes much simpler, as in F#
No, there is no way to do this more easily in the current version of C#. There was a new feature in the C# 6.0 prereleases called Primary Constructors to solve this, but it was removed before the final release. https://www.c-sharpcorner.com/UploadFile/7ca517/primary-constructor-is-removed-from-C-Sharp-6-0/
Currently, I believe the C# team are working on adding records to the language: https://github.com/dotnet/roslyn/blob/features/records/docs/features/records.md - this should make working with simple data classes much simpler, as in F#
answered 1 hour ago
Jonas HøghJonas Høgh
7,25311737
7,25311737
add a comment |
add a comment |
If you define your variables first, you can use visual studios' "Quick actions" tool to generate a constructor for you; this gives you a choice of the currently-defined class fields to include.
using this will insert a constructor class with all your selected fields as parameters, and it will assign the values to the fields.
This will not reduce the amount of code, but it will cut back on the amount of typing you need
add a comment |
If you define your variables first, you can use visual studios' "Quick actions" tool to generate a constructor for you; this gives you a choice of the currently-defined class fields to include.
using this will insert a constructor class with all your selected fields as parameters, and it will assign the values to the fields.
This will not reduce the amount of code, but it will cut back on the amount of typing you need
add a comment |
If you define your variables first, you can use visual studios' "Quick actions" tool to generate a constructor for you; this gives you a choice of the currently-defined class fields to include.
using this will insert a constructor class with all your selected fields as parameters, and it will assign the values to the fields.
This will not reduce the amount of code, but it will cut back on the amount of typing you need
If you define your variables first, you can use visual studios' "Quick actions" tool to generate a constructor for you; this gives you a choice of the currently-defined class fields to include.
using this will insert a constructor class with all your selected fields as parameters, and it will assign the values to the fields.
This will not reduce the amount of code, but it will cut back on the amount of typing you need
answered 1 hour ago
ThisIsMeThisIsMe
211
211
add a comment |
add a comment |
The answer to your question is no, but you could use properties to get a similar fix:
class MyClass
{
public int Var1 {get;set;}
public int Var2 {get;set;}
public int Var3 {get;set;}
public int Var4 {get;set;}
public MyClass(){
}
}
void Main()
{
var myClass = new MyClass
{
Var1 = 1,
Var2 = 2,
Var3 = 3,
};
}
5
Per .NET coding convention, properties have first letter upper-case
– Teejay
1 hour ago
5
Object initializers are nice, but if you have some properties that must be initialized when creating an instance they are not a substitute replacement for constructor arguments.
– Zohar Peled
1 hour ago
1
I dont see any difference here. The initialisation was centralised in the constructor , now every time you want to accomplish that logic you'll use this object initialiser syntax. This does not answer the question.
– Zack ISSOIR
1 hour ago
add a comment |
The answer to your question is no, but you could use properties to get a similar fix:
class MyClass
{
public int Var1 {get;set;}
public int Var2 {get;set;}
public int Var3 {get;set;}
public int Var4 {get;set;}
public MyClass(){
}
}
void Main()
{
var myClass = new MyClass
{
Var1 = 1,
Var2 = 2,
Var3 = 3,
};
}
5
Per .NET coding convention, properties have first letter upper-case
– Teejay
1 hour ago
5
Object initializers are nice, but if you have some properties that must be initialized when creating an instance they are not a substitute replacement for constructor arguments.
– Zohar Peled
1 hour ago
1
I dont see any difference here. The initialisation was centralised in the constructor , now every time you want to accomplish that logic you'll use this object initialiser syntax. This does not answer the question.
– Zack ISSOIR
1 hour ago
add a comment |
The answer to your question is no, but you could use properties to get a similar fix:
class MyClass
{
public int Var1 {get;set;}
public int Var2 {get;set;}
public int Var3 {get;set;}
public int Var4 {get;set;}
public MyClass(){
}
}
void Main()
{
var myClass = new MyClass
{
Var1 = 1,
Var2 = 2,
Var3 = 3,
};
}
The answer to your question is no, but you could use properties to get a similar fix:
class MyClass
{
public int Var1 {get;set;}
public int Var2 {get;set;}
public int Var3 {get;set;}
public int Var4 {get;set;}
public MyClass(){
}
}
void Main()
{
var myClass = new MyClass
{
Var1 = 1,
Var2 = 2,
Var3 = 3,
};
}
edited 1 hour ago
answered 1 hour ago
NeilNeil
4,84211537
4,84211537
5
Per .NET coding convention, properties have first letter upper-case
– Teejay
1 hour ago
5
Object initializers are nice, but if you have some properties that must be initialized when creating an instance they are not a substitute replacement for constructor arguments.
– Zohar Peled
1 hour ago
1
I dont see any difference here. The initialisation was centralised in the constructor , now every time you want to accomplish that logic you'll use this object initialiser syntax. This does not answer the question.
– Zack ISSOIR
1 hour ago
add a comment |
5
Per .NET coding convention, properties have first letter upper-case
– Teejay
1 hour ago
5
Object initializers are nice, but if you have some properties that must be initialized when creating an instance they are not a substitute replacement for constructor arguments.
– Zohar Peled
1 hour ago
1
I dont see any difference here. The initialisation was centralised in the constructor , now every time you want to accomplish that logic you'll use this object initialiser syntax. This does not answer the question.
– Zack ISSOIR
1 hour ago
5
5
Per .NET coding convention, properties have first letter upper-case
– Teejay
1 hour ago
Per .NET coding convention, properties have first letter upper-case
– Teejay
1 hour ago
5
5
Object initializers are nice, but if you have some properties that must be initialized when creating an instance they are not a substitute replacement for constructor arguments.
– Zohar Peled
1 hour ago
Object initializers are nice, but if you have some properties that must be initialized when creating an instance they are not a substitute replacement for constructor arguments.
– Zohar Peled
1 hour ago
1
1
I dont see any difference here. The initialisation was centralised in the constructor , now every time you want to accomplish that logic you'll use this object initialiser syntax. This does not answer the question.
– Zack ISSOIR
1 hour ago
I dont see any difference here. The initialisation was centralised in the constructor , now every time you want to accomplish that logic you'll use this object initialiser syntax. This does not answer the question.
– Zack ISSOIR
1 hour ago
add a comment |
Short: No, Long: Yes, there is a hack.
You can use a mix of reflection and storing the parameter in a temporary array to achieve that.
class TestClass
{
public string var1 { get; set; }
public string var2 { get; set; }
public string var3 { get; set; }
public TestClass(string var1, string var2, string var3) : base()
{
var param = new { var1, var2, var3 };
PropertyInfo[] info = this.GetType().GetProperties();
foreach (PropertyInfo infos in info) {
foreach (PropertyInfo paramInfo in param.GetType().GetProperties()) {
if (infos.Name == paramInfo.Name) {
infos.SetValue(this, paramInfo.GetValue(param, null));
}
}
}
}
}
This basically loops through the properties and check's whether the name equals the parameter name, which have been stored in a temporary array (you can't get the parameter value with reflection), and assigns it if they match.
Note: I do not recommend assigning properties like that, but for the sake of proof that it's possible I came up with this.
New contributor
add a comment |
Short: No, Long: Yes, there is a hack.
You can use a mix of reflection and storing the parameter in a temporary array to achieve that.
class TestClass
{
public string var1 { get; set; }
public string var2 { get; set; }
public string var3 { get; set; }
public TestClass(string var1, string var2, string var3) : base()
{
var param = new { var1, var2, var3 };
PropertyInfo[] info = this.GetType().GetProperties();
foreach (PropertyInfo infos in info) {
foreach (PropertyInfo paramInfo in param.GetType().GetProperties()) {
if (infos.Name == paramInfo.Name) {
infos.SetValue(this, paramInfo.GetValue(param, null));
}
}
}
}
}
This basically loops through the properties and check's whether the name equals the parameter name, which have been stored in a temporary array (you can't get the parameter value with reflection), and assigns it if they match.
Note: I do not recommend assigning properties like that, but for the sake of proof that it's possible I came up with this.
New contributor
add a comment |
Short: No, Long: Yes, there is a hack.
You can use a mix of reflection and storing the parameter in a temporary array to achieve that.
class TestClass
{
public string var1 { get; set; }
public string var2 { get; set; }
public string var3 { get; set; }
public TestClass(string var1, string var2, string var3) : base()
{
var param = new { var1, var2, var3 };
PropertyInfo[] info = this.GetType().GetProperties();
foreach (PropertyInfo infos in info) {
foreach (PropertyInfo paramInfo in param.GetType().GetProperties()) {
if (infos.Name == paramInfo.Name) {
infos.SetValue(this, paramInfo.GetValue(param, null));
}
}
}
}
}
This basically loops through the properties and check's whether the name equals the parameter name, which have been stored in a temporary array (you can't get the parameter value with reflection), and assigns it if they match.
Note: I do not recommend assigning properties like that, but for the sake of proof that it's possible I came up with this.
New contributor
Short: No, Long: Yes, there is a hack.
You can use a mix of reflection and storing the parameter in a temporary array to achieve that.
class TestClass
{
public string var1 { get; set; }
public string var2 { get; set; }
public string var3 { get; set; }
public TestClass(string var1, string var2, string var3) : base()
{
var param = new { var1, var2, var3 };
PropertyInfo[] info = this.GetType().GetProperties();
foreach (PropertyInfo infos in info) {
foreach (PropertyInfo paramInfo in param.GetType().GetProperties()) {
if (infos.Name == paramInfo.Name) {
infos.SetValue(this, paramInfo.GetValue(param, null));
}
}
}
}
}
This basically loops through the properties and check's whether the name equals the parameter name, which have been stored in a temporary array (you can't get the parameter value with reflection), and assigns it if they match.
Note: I do not recommend assigning properties like that, but for the sake of proof that it's possible I came up with this.
New contributor
New contributor
answered 59 mins ago
ShawnShawn
313
313
New contributor
New contributor
add a comment |
add a comment |
In simple terms not you cant. The use of this is not necessary, but it is elegant to do and shows intent as to reinforce the fact that a variable is part of the context of a class.
However the problem here arise from the fact that both your parameters and instance variables have the same names.
The compiler is unable to differentiate between same name variables(it night complaints of circular reference).
The use of this
keyword allow us we tell the compiler that we are referring to the current instance of that variable.
I think that you can improve the code and coding per se with a better Naming approch for your variables.
Eg var1 var2 var3
they don't really say anything and make the code hard to understand.
Try to be specific and verbose :
Eg firstName, lastName, address and so forth. They are self-explanatory.
add a comment |
In simple terms not you cant. The use of this is not necessary, but it is elegant to do and shows intent as to reinforce the fact that a variable is part of the context of a class.
However the problem here arise from the fact that both your parameters and instance variables have the same names.
The compiler is unable to differentiate between same name variables(it night complaints of circular reference).
The use of this
keyword allow us we tell the compiler that we are referring to the current instance of that variable.
I think that you can improve the code and coding per se with a better Naming approch for your variables.
Eg var1 var2 var3
they don't really say anything and make the code hard to understand.
Try to be specific and verbose :
Eg firstName, lastName, address and so forth. They are self-explanatory.
add a comment |
In simple terms not you cant. The use of this is not necessary, but it is elegant to do and shows intent as to reinforce the fact that a variable is part of the context of a class.
However the problem here arise from the fact that both your parameters and instance variables have the same names.
The compiler is unable to differentiate between same name variables(it night complaints of circular reference).
The use of this
keyword allow us we tell the compiler that we are referring to the current instance of that variable.
I think that you can improve the code and coding per se with a better Naming approch for your variables.
Eg var1 var2 var3
they don't really say anything and make the code hard to understand.
Try to be specific and verbose :
Eg firstName, lastName, address and so forth. They are self-explanatory.
In simple terms not you cant. The use of this is not necessary, but it is elegant to do and shows intent as to reinforce the fact that a variable is part of the context of a class.
However the problem here arise from the fact that both your parameters and instance variables have the same names.
The compiler is unable to differentiate between same name variables(it night complaints of circular reference).
The use of this
keyword allow us we tell the compiler that we are referring to the current instance of that variable.
I think that you can improve the code and coding per se with a better Naming approch for your variables.
Eg var1 var2 var3
they don't really say anything and make the code hard to understand.
Try to be specific and verbose :
Eg firstName, lastName, address and so forth. They are self-explanatory.
edited 43 mins ago
answered 1 hour ago
Alex LeoAlex Leo
7651213
7651213
add a comment |
add a comment |
Fredrik Persson is a new contributor. Be nice, and check out our Code of Conduct.
Fredrik Persson is a new contributor. Be nice, and check out our Code of Conduct.
Fredrik Persson is a new contributor. Be nice, and check out our Code of Conduct.
Fredrik Persson is a new contributor. Be nice, and check out our Code of Conduct.
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54824786%2fhow-to-store-all-ctor-parameters-in-fields%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
2
As of my knowledge no! :(
– abhinavxeon
1 hour ago
No. but fields and arguments should have similar yet different names - for instance, having fields always begin with an underscore is one fairly common way to distinguish them from anything else. You would still need to explicitly set the fields in the constructor, but you wouldn't have to use the
this
keyword for it: (i.e_var1 = var1
)– Zohar Peled
1 hour ago
1
No, but just to speed things up you do something like this (in VS): docs.microsoft.com/en-us/visualstudio/ide/reference/…
– Nanna
1 hour ago
1
Write the parameter (e.g.
int var1
). Selectvar1
and pressControl .
. Options will appear to write the assignment code for you.– mjwills
1 hour ago
Of course no. I mean, you can use Properties instead or use quick actions and refactoring, but to make it automatically assign your fields, because you are tired to write same thing over and over, no.
– SeM
1 hour ago