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;
Related
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 1 year ago.
Improve this question
When I checked the attributes for equality, I noticed that they already have Equals method that compares the fields. For custom classes this comparison does not occur, since it is bad for performance, but why was an exception made for attributes?
Here's the code to make sure:
public class MyAttribute : Attribute
{
public int Value { get; }
public MyAttribute(int value) => Value = value;
}
public class MyClass
{
public int Value { get; }
public MyClass(int value) => Value = value;
}
public class Test
{
[Test]
public void TestEquals()
{
var myAttributeLeft = new MyAttribute(1);
var myAttributeRight = new MyAttribute(1);
var attributeEqualityResult = myAttributeLeft.Equals(myAttributeRight);
Console.WriteLine(attributeEqualityResult); // true
var myClassLeft = new MyClass(1);
var myClassRight = new MyClass(1);
var classEqualityResult = myClassLeft.Equals(myClassRight);
Console.WriteLine(classEqualityResult); // false
}
}
Custom attributes are not intended for use as domain objects: they are explicitly intended to represent metadata that are hard-coded at compile time. Assuming they are used as intended, this gives them a few special properties:
There are limits on the types that they are allowed to use: typically native types like int and string, and arrays of those native types.
The number of items that could be put into an array on the type is bounded by the number of items that are written into an actual code file.
In domain models it could create enormous performance penalties to compare the values of fields, properties, and elements of collections: you don't know how big the object structure for a given class might be, and a collection could have millions of items in it. But the restrictions mentioned above mean that the cost of an equality comparison for custom attributes is pretty well bounded. Evidently the creators of .NET felt that this made it worthwhile to give the base class value semantics, although the documentation includes remarks that recommend overriding the default implementation to use object equality or hard-coded value semantics instead.
Short answer: System.Attribute implements its own implementation of Equals which is different from the one in System.Object (from which MyClass class inherits)
You can find a more detailed answer on ms docs
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
My C# program needs to receive xml data and store it in sql database. I have Batches which has many Instructions. I implement the classes thusly:
class Batch
{
public string batchUID { get; set; }
public Instruction[] instructionArray { get; set; }
}
class Instruction
{
public string instructionUID { get; set; }
}
My program runs like this
Batch myBatch = new Batch();
myBatch.instructionArray = new Instruction[3];
myBatch.instructionArray[0] = new Instruction();
SomeFunc(myBatch.instructionArray[0]);
public void SomeFunc(Instruction instruction)
{
// How do I do the following?
console.write( instruction.OWNER.batchUID )
}
I have tried to search for this extensively but every result is related to inheritance, inner/outer classes, etc. I would like to avoid creating a batchUID method inside class Instruction if possible.
You can pass an instance of Batch to the constructor of Instruction, and then store a reference to that Batch that you can expose with a property. (This was already shown in another answer - I'm repeating it because it provides context to what I'm going to add next.)
class Instruction
{
public Instruction(Batch parent)
{
Parent = parent;
}
public Batch Parent { get; private set; }
public string InstructionUID { get; set; }
}
Now Instruction has a Parent property that returns a Batch.
But there's a gap. If you call
var parent = batch.Instruction[0].Parent
is parent == batch? It looks like that's the intent. The Instruction contains a reference to the Batch that contains it.
But nothing is enforcing that. For example, I could do this:
someBatch.Instruction[0] = someOtherBatch.Instruction[1];
Now someBatch contains an array of Instruction, but at least one of them actually has someOtherBatch as its parent.
Maybe that possibility is no big deal, but I think that if Parent is meant to refer to the Batch containing the Instruction but it might not, then you haven't actually accomplished what you're aiming for.
I'd recommend creating a separate class that contains both a Batch and an Instruction. (Perhaps ParentInstructionRelation?)
public class ParentInstructionRelation
{
Batch Parent {get;private set;}
Instruction Instruction {get;private set;}
public ParentInstructionRelation(Batch parent, Instruction instruction)
{
Parent = parent;
Instruction = instruction;
}
}
That way Instruction doesn't need a reference to its parent. It probably shouldn't have a reference to its parent. What if the same Instruction is in two different instances of Batch? Which one is the parent?
But if Batch needs to expose an Instruction and a reference to itself, then it can do that by returning a ParentInstructionRelation. Or a class that reads the Instruction from Batch can create that relationship.
var instructions = batch.InstructionArray
.Select(instruction => new ParentInstructionRelation(batch, instruction));
Your code has an issue:
myBatch.instructionArray = new Instruction[3];
That will just create an array with 3 null values, not 3 instances of Instruction. This is because a class is a reference type and it will not be instantiated automatically here (structs however are, since they are value types and get all their values initialized in a default constructor which is then called). You still have to create those instructions before passing them to your method as you'd effectively just be passing null.
Then, when creating an instance of Instruction, just pass the parent as a parameter, and remember it in the class, like this:
class Instruction
{
public Instruction(Batch parent)
{
Parent = parent;
}
public Batch Parent { get; private set; }
public string InstructionUID { get; set; } // Please start properties with an uppercase letter
}
This way, you can access the Batch instance to which the Instruction instance belongs later on.
Batch myBatch = new Batch();
myBatch.InstructionArray = new Instruction[3];
// TODO: Create the instances here, the array is just null null null now!
myBatch.InstructionArray[0] = new Instance(myBatch); // example
SomeFunc(myBatch.InstructionArray[0]);
public void SomeFunc(Instruction instruction)
{
Console.Write(instruction.Parent.BatchUID)
}
If this is good design is another question, the Instruction might have the SomeFunc stuff inside itself, but I'm not sure what the project should achieve eventually.
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 6 years ago.
Improve this question
In a user-defined class, I'd like to leave the type of a List ambiguous so that I could have a list of strings or integers or tuples in separate instances of the class (that is to say, each list would be of only one type, but different instances of the class would different types). I currently have something like:
public Result
{
private List<dynamic> _vaguelist;
public List<dynamic> vaguelist {
get
{
return _vaguelist;
}
set
{
_vaguelist = value;
}
}
}
But, I'm pretty sure I'm not using the dynamic type properly. I think I would need a constructor that creates a new List where T gets determined from the GetType() of the first value added to the Class. Or write the List to be designated a certain type when it is initialized.
In short, how can I define a list within a class such that the type of its values can either be inherent of whatever is added to the list or specified when the class is instantiated? (values within a single list will all be of ONE type).
I think you have two options, the first one beign the best approach, will only work if you know the list will be of a certain type.
public class Result<T>
{
private List<T> _vaguelist = new List<T>();
public List<T> vaguelist {
get
{
return _vaguelist;
}
set
{
_vaguelist = value;
}
}
}
Result a = new Result<string>();
a.vaguelist.Add("1234");
Result b = new Result<int>();
a.vaguelist.Add(1234);
The second option will work if you wan't to add more than one type into the list o you won't know what you're putting into the list
public class Result
{
private List<object> _vaguelist;
public List<object> vaguelist {
get
{
return _vaguelist;
}
set
{
_vaguelist = value;
}
}
}
Result a = new Result();
a.vaguelist.Add("1234");
a.vaguelist.Add(1234);
The problem with this approach is that you will have to cast every single item in the list in order to take advantage of the type the item is.
Making use of the first approach, you could implement it like this:
public class Result<T>
{
private List<T> _vaguelist = new List<T>();
public List<T> vaguelist {
get
{
return _vaguelist;
}
set
{
_vaguelist = value;
}
}
}
public abstract class Result
{
public static Result<T> NewResultFromItem<T>(T item)
{
Result<T> result = new Result<T>();
result.vaguelist.Add(item);
return result;
}
}
string item1 = "123";
string item2 = "234";
var result = Result.NewResultFromItem(item1);
result.vaguelist.Add(item2);
You are asking for both type safety and type agnosticism (I just made up that word), which you cannot have both at the same time. Suppose you would find a way to make the list flip to a type safe collection at runtime when the first item is added. Who or what would be able to use it as such if you cannot code against it? The compiler will not know what it is going to be at runtime so there is not much that can be done for type safety. At runtime you would still have to figure out what you are dealing with so from a coding perspective it would still be just a list of objects.
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).
Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 9 years ago.
Improve this question
There is a public interface in the project with a value as follows:
Name3D MyName3D { get; set; }
Now in another location I am using a public sealed class, I added the namespace / using System.Interfacename. Now I want to set it like follows:
private readonly Interfacename m_MyName3D ;
private const string 3DName = ##;
How would i go aobut setting it up so ## is the value of MyName3D. Again I haven't done anything like this before. Just wanted to give it a try?
Would be really appreciated if I could get some detail onto how it works.
Update One
Do you mean this?
using Interfacename;
public sealed class InfoController : AsyncController
{
private readonly Interfacename m_MyName3D ;
private const string 3DName = ##;
You can not assign anything to a const member at runtime. You can however make 3DName a readonly property and relay the get accessor to the interface:
private string 3DName { get { return m_MyName3D.MyName3D; } }
But maybe I did not get what you are trying to do, if so please describe it more clearly.
edit: you are using two types for 3DName, Name3D and string. If Name3D has no conversion operators you need to use it throughout the property.
private Name3D 3DName { get { return m_MyName3D.MyName3D; } }
If you really need to return a string the you need to write a string conversion operator for Name3D:
struct/class Name3D
{
public static implicit operator string(Name3D name)
{
return name.whatever; // this needs to be the data holding member(s) of Name3D
}
}