Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am new to programming, could someone please explain me difference between constructor and property in context to C#.
since both used to initialized your class fields, & also which one to choose in a given situation .
Besides all the technical stuff, a good rule of thumb is to use constructor parameters for mandatory things, properties for optional things.
You can ignore properties (hence optional), but you can't ignore constructor parameters (hence mandatory).
For everything else, I'd recommend reading a C# beginners book or tutorial ;-)
A property is just a class member that can be initialized when ever.
Like so:
var myClass = new MyClass();
myClass.PropertyA = "foo";
myClass.PropertyB = "bar";
A constructor is run when the class is created and can do various things. In your "scenario" it would probably be used to initialize members so that the class is in a valid state upon creation.
Like so:
var myClass = new MyClass("foo", "bar");
Constructor is a special type of method from the class to create the object itself. You should use it to initialize everything necessary to make the object work as expected.
From MSND Constructor:
When a class or struct is created, its constructor is called.
Constructors have the same name as the class or struct, and they
usually initialize the data members of the new object.
Properties enable a class to store, setting and expose values needed for the object. You should create to help in the behavior for the class.
From MSND Property:
A property is a member that provides a flexible mechanism to read,
write, or compute the value of a private field. Properties can be used
as if they are public data members, but they are actually special
methods called accessors. This enables data to be accessed easily and
still helps promote the safety and flexibility of methods.
Example:
public class Time
{
//
// { get; set; } Using this, the compiler will create automatically
// the body to get and set.
//
public int Hour { get; set; } // Propertie that defines hour
public int Minute { get; set; } // Propertie that defines minute
public int Second { get; set; } // Propertie that defines seconds
//
// Default Constructor from the class Time, Initialize
// each propertie with a default value
// Default constructors doesn't have any parameter
//
public Time()
{
Hour = 0;
Minute = 0;
Second = 0;
}
//
// Parametrized Constructor from the class Time, Initialize
// each propertie with given values
//
public Time(int hour, int Minute, int second)
{
Hour = hour;
Minute = minute;
Second = second;
}
}
Properties should be used to validate the values passed as well, for exemple:
public int Hour
{
//Return the value for hour
get
{
return _hour;
}
set
{
//Prevent the user to set the value less than 0
if(value > 0)
_hour = 0;
else
throw new Exception("Value shoud be greater than 0");
}
private int _hour;
Hopes this help you to understand! For more information about C# take a look at Object-Oriented Programming (C# and Visual Basic).
Related
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
I have been struggling with a the concept mentioned in the title. I've done a good deal of research and have found some good examples and I have attempted to implement some of them but have reached a road block.
I initially had a class that looked like this:
namespace sysVer
{
public class testSuite
{
/* there is a bunch of test hardware setup
* and acquisition also that is not shown
*/
public struct testResultInfo
{
public testStatus testStat;
public bool warning, error;
public string warnStr, errStr, infoStr, muxDataStr;
public double measDecVal;
public Int16 measIntVal;
};
// NOTE there is no default constructor
public static testResultInfo testCase1()
{
}
public static testResultInfo testCase2()
{
}
public static testResultInfo testCase3()
{
}
// there are about 100 more
}
}
And using a windows form with 105 of checkboxes and a dictionary to determine which function the user wants to run, I was able to call the functions by a string using Invoke Member as follows:
// first attempt
namespace sysVer
{
public partial class SysVerForm : Form
{
public static Pdgu1553ver.testResultInfo tcResult = new Pdgu1553ver.testResultInfo ( )
{
testStat = Pdgu1553ver.testStatus.pass,
warning = true,
error = true,
warnStr = "This is a warning",
errStr = "This is an error",
infoStr = "This is info",
muxDataStr = "Mux data of some sort",
measDecVal = 69.69,
measIntVal = 69
};
// for loop that iterates over checkbox checked items
foreach ( var checkedItem in checkedItems )
{
var funcName = "";
// retrieve function name from dictionary
tcToFuncDic.TryGetValue ( checkedItem.ToString ( ), out funcName );
tcResult = ( testSuite.testResultInfo ) typeof ( testSuite ).InvokeMember
(
funcName,
BindingFlags.InvokeMethod |
BindingFlags.Public |
BindingFlags.Static,
null,
null,
null
);
}
}
}
But I ran into a problem here. When InvokeMember is called the static method is executed and a return type is received but I am not sure if the method is just called or is an actual instance of the class created using the default constructor? I started noticing that private attributes of this class set during one call were not there during another call to a different static function that needed them.
I assumed that I needed an instance of my class so I changed to the following:
namespace sysVer
{
public class testSuite
{
/* there is a bunch of test hardware setup
* and acquisition also that is not shown
*/
public struct testResultInfo
{
public testStatus testStat;
public bool warning, error;
public string warnStr, errStr, infoStr, muxDataStr;
public double measDecVal;
public Int16 measIntVal;
};
// constructor
public testSuite()
{
/* Here I initialize hardware, set variables, and
* run a few other tasks. All of which need to be done
* an exist before this object can be used
*/
}
public testResultInfo testCase1()
{
}
public testResultInfo testCase2()
{
}
public testResultInfo testCase3()
{
}
//... there are about 100 more
}
}
Now, I hit another wall. I needed to do something like this:
testSuite myTest = new testSuite();
var blah = myTest.InvokeMember(
funcName,
BindingFlags.InvokeMethod |
BindingFlags.Public |
BindingFlags.Static,
null,
null,
null
);
But my class does not contain that method. Looking into that I learned that I could change my class to inherit from 'Type' and that I would have to override about 50 or so abstracts from 'Type'. I started down this path but feel that it is likely more work than I need to do here.
I need to have an instance of my class and need to be able to deduce at runtime which non-static method to call. Of the many posts I've read these two: How to invoke a non static method by reflection and invoke non static method in c#
seem to be pushing me in the right direction but I'm still missing something somewhere.
I've already put lots of time in overriding all those functions but am stuck there with how to actually implement the overridden InvokeMember function, I'd hate to undo all that work to try to do something else at this point.
As always, any advice is greatly appreciate. Thank you for your time and consideration.
I get the sense you're convoluting a lot of assumptions and concerns with static, structs, reflection, etc. and losing track of where you want to go. You've apparently tried to solve the wrong problems the wrong way. But I'll address your questions one at a time.
I am not sure if the method is just called or is an actual instance of the class created using the default constructor?
Why would you think that? You didn't post the code of the test methods but I can assure you that InvokeMember actually invokes the member.
I started noticing that private attributes of this class set during one call were not there during another call to a different static function that needed them.
Probably because the test methods create a new testResultInfo each time, but without the code it's impossible to know. But I don't see why that is a problem. What data do you need to "carry over"? Maybe you need a static testResultInfo property on testSuite that you can reuse within the methods?
Looking into that I learned that I could change my class to inherit from 'Type'
I can't see any reason whatsoever why you'd need to do that or what you think that would solve.
Stop trying top band-aid problems that were created by trying to fix other problems, possibly in the wrong way. Back up, analyze your program and think about where different instances are created? should these test methods magically know about the instance that you've created in the form or should they be given that instance somehow? How should you do that? Should you make it an input parameter? Or a static property of the test suite?
This question already has answers here:
C# 3.0 auto-properties — useful or not? [closed]
(17 answers)
What is the difference between a field and a property?
(33 answers)
Closed 7 years ago.
Excuse me if my question is pretty much about code-style, but for simple cases which of the bellow is better?
CASE 1:
private static int number = 1;
public static int Number
{
get { return number; }
set { number = value; }
}
CASE 2:
public static int Number
{
get;
set;
}
I think case 2 is better because, when you have many properties in your class they won't consume so much space and the filesize will be reduced.
The syntax below is called auto properties, it doesn't matter in the terms of file size since in compilation time, a field is generated anyway (see, decompilation in the end of the answer) and there are get and set methods in the compilation results in both cases.
Auto properties allow you to keep your code more organized and short which is good for your code maintainability and readability, therefore you should prefer them when possible.
We will put aside the "In field without auto-property you can assign default value" topic for a second (also, it is possible now in auto-properties too in c# 6.0), sometimes, you want to run some more code inside the get or set methods of the property, like invoking event handles or validating the values, that's where standard property declaration comes into the picture, for example:
private int mNumber;
public int Number
{
get
{
return Number;
}
set
{
if (Number == 8)
{
throw new CannotReceive8Exception();
}
else
{
mNumber = value;
}
}
}
If you look at the decompiled code of this code:
public int Number { get; set; }
You will see that the compiler has added a background private field anyway:
While there is no difference to the compiler, since it would generate the fields for you, I prefer to leave my code clean and just use
public int Num {get;set;}
in one line, since there is no supreme meaning to explicitly typing the code and keeping it in one line allows me to differentiate properties like this from methods, which span across multiple lines at glance.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I am a beginner programmer looking for some help with c#.
I am writing a program based on a framework and need to create a data member of a class, then initialize the data member to something.
Next,I need to make a property to get and set the data member.
Also, if someone could provide some information on how to typecast the property that would be great.
I'm just looking for examples and general information here. I checked google and only got links from MSDN but did not understand the content.
Thanks!
Here is a basic explanation, using code:
//Class Definition
public class MyClass
{
//Data Member with inline initialization
private int myInt = 1;
//Standard property
public int MyIntProp
{
get { return myInt; }
set { myInt = value; }
}
//Auto-property, generates the same getter/setter as above with a "hidden" backing property.
public String MyStringProp {get; set;}
//Class constructor, great for initialization!
public MyClass()
{
//Set the property to an initial value
MyStringProp = "Hello World";
}
}
Typecasting is another monster. You have to be careful when doing it, because very few types can be cast to others. The number types can generally be cast to one another (although you can lose data), and derived types can be cast to their base types, but that is about it.
An example (safe) cast of a number would be:
int myInt = 2;
long myLong = (long)myInt;
That is called a "C-Style" cast (because it's how you do it in C) and is generally how you cast numbers. There are other styles and functions to do the cast of course.
#Iahsrah's suggestion is also a good place to start.
A basic type is a class which looks like this:
public class MyType
{
}
You can create a property of this on another class like this:
public class AnotherType
{
public MyType InlinePropertyName { get; set; }
// Simple propertoes require no implimentation (above), or you can explicitly control it all (below)
private MyType _explicitPropertyName;
public MyType ExplicitPropertyName {
get {
return _explicitPropertyName;
}
set {
_explicitPropertyName = value;
}
}
}
The you can easily access from elsewhere in your program like this:
var myType = new MyType();
var anotherType = new AnotherType();
anotherType.InlinePropertyName = myType;
This question already has answers here:
Public Fields versus Automatic Properties
(14 answers)
Closed 9 years ago.
Example 1:
class Class1
{
public static int A = 1;
}
Example 2:
class Class2
{
private static int _A = 1;
public static int A
{
get
{
return _A;
}
set
{
_A = value;
}
}
}
Assuming that I don't want to do any validation and perform any extra functions. I just want to hold the plain data. Both Class1.A and Class2.A have the same result. New number can be assigned to both too. So what is the different for doing this? Is there any benefits? Why and When should I use them?
If there is no difference between them, I should use Example 1, as Example 1 only requires 1 line of code and Example 2 requires 6-10 lines. Do you agree?
The technical difference is the presence of get and set accessors. You can customize either or both to do more that just get or set the value.
The practical difference is that many data-binding methods (including most if not all of the .NET controls) use reflection to bind to properties only - they do not support binding to fields directly.
If you plan to bind the properties of your class to a UI control (DataGrid, TextBox, etc.), or if there's the slightest chance that you might customize the get/set accessors in the future, then make the properties. It is a breaking change to change a field to a property.
Many coding standards (including FxCop) hold that you should use properties instead of fields for public data.
If lines of code are a concern you can use auto-implemented properties:
class Class2
{
public static int A {get; set; }
}
You can later add logic to the get/set accessors without breaking users of your class.
I have a class that in order to do it's job needs to have 8 different property values set.
I want to make sure that all 8 properties are set before trying to execute a method.
I currently have all the parameters passed in and set via the constructor.
Is there a better way to do this?
You can allow the object to be created without specifying values for all the properties and then the method would throw an InvalidOperationException if called before the object state is valid for the method call to execute, which in this case would mean that all 8 properties would have valid values.
This way you give more flexibility to the consumer. It can create a new instance at one moment, set it's properties at another and only then call the method. This is a "pattern" that is used through the .NET codebase and to which developers are already used.
Update:
This also simplifies things if you're adding other methods that don't need the full set of properties to be initialized. Yes we could add another constructor overload with the new set of properties, but what if we have 2 methods that both need one property of the same type to be initialized? This is not solvable by using constructor overloads.
In my opinion if a class requires these 8 objects in order to function then they should be passed into the constructor and by no other means. I'm a big fan of dependency injection anyway, but this method also allows for better unit testing by passing in mocked objects and such.
you could consolidate the parameters into a Parameter Object and just pass that instead.
If you were using this class from XAML you would make all 8 properties individually settable and throw an exception if somebody tries to execute a method without them all set. It's also possible that you would want to "freeze" the object once a method was called and throw an exception if somebody tries to set a property on a "frozen" object.
I'm not going to pass judgement on which method is better, though.
A constructor is the only way to do it at compile time. The other option would be to throw an exception if not all the parameters have been set.
Give them default values?
Maybe you can give a bit more of the context to let us help you!
Use setter in the properties. When property is used by the method and it is not set already, setter would do it for you. This is not the recommended approach thogh but might be needed in some situations.
Some thing similar would work
Class SomeClass
{
string name;
string Name
{
set
{
if (name == null)
name = value;
}
}
}
The constructor sounds like the best way to do this since it will be verified at compile tile. Of course, you could have default values for some or all of the properties and then chain constructors, so that not every property needs to be set in the constructor. Something like:
public class Person
{
public string Name { get; set; }
public double Height { get; set; }
public DateTime DoB { get; set; }
public Person(string name, double height, DateTime dob) : this(name, height)
{
this.DoB = dob;
}
public Person(string name, double height)
{
this.Name = name;
this.Height = height;
this.DoB = DateTime.Now.Date;
}
}
This means you can construct a new Person object using either two or three parameters, but all will be set (but if you use two then DOB will get a default of today):
Person person1 = new Person("Geoff", 1.8, new DateTime(1950, 5, 12));
Person person2 = new Person("John", 1.54); // Gets default DOB
You can use an object initializer if you are using c# 3.0 onwards. This is arbitrary whether it's 'better' or not.