Is there a DRYer way to initialise class values 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 2 years ago.
Improve this question
Let's say I have a class:
class Foo
{
private int blah;
private char bleh;
private string bluh;
//...
public Foo()
{
}
}
Now normally, I have to initialise it like this:
public Foo(int blah, char bleh, string bluh,...)
{
this.blah=blah;
this.bleh=bleh;
this.bluh=bluh;
//...
}
This is dull and doesn't seem to follow the "Don't Repeat Yourself" principle so I'm looking for a better solution. Can this be done DRYer?
Edit: Changed variables to private to reflect a more common use case.

Use object initialization when initializing your variables/properties instead, if you really don't want to repeat yourself
Like this
Foo f = new foo{
blah = 1;
bleh = 'A';
bluh = "something";
};
And also, don't use public accessor on your fields, that's not good.

class Foo
{
public readonly int blah;
public readonly char bleh;
public readonly string bluh;
//...
public Foo(int blah, char bleh, string bluh)
{
this.blah=blah;
this.bleh=bleh;
this.bluh=bluh;
//...
}
}
Can be written as a record type and is a good candidate as its immutable. To rewrite the above as a record just use
public record Foo(int blah, char bleh, string bluh);
Much cleaner in my opinion and seems to be what you're after.

Related

Many const integers in a program [closed]

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 6 years ago.
Improve this question
I am a C# junior programmer and running into a requirement of defining a lot of constant integers in my program (up to 5000 of them). I would like to know whether doing something like this in my C# program file
const int a=1;
const int b=2;
....
const int x5000=5000;
is practical in a business application. My supervisor tells me to leave them in a separate file then initialize a variable to store them when the program starts to run. But I find that method is no good because any user can change the file.
I don't know if there is any better way to do this. I also think all of constant things are still apparent in a compiled C# file even when I view it with notepad. I would want all of the readable text in source files after compiled into a pe to be hexificated.
A common method of handling this is to declare classes that holds your constant values and gives them meaningful names.
With thousands of constants it may be useful to use more than one class if the constants can be grouped meaningfully, usually around how they are used.
public class Constants
{
public int A { return 1; }
public int B { return 2; }
public int X5000 { return x5000; }
}
These classes are then passed into any class that needs the constants they hold.
Additionally, if desired, the class can be initialized with the values from an external source during construction.
The main point is to give the constants meaningful names, group by use and abstract away where the values are coming from.
In such cases I'm trying to gather consts into logical groups. Each group - one class:
public sealed class ABCConsts{
public const int A=1;
public const int B=2;
...
}
...
public sealed class XConst{
public const int X5000 = 5000;
}
it's better to put each class into separate file.
PS: good stuf to futher reading - Static readonly vs const fields
You may take a look at enum
and add a static class, something like ErrorCodeManager to access the enum, just in cause of refactoring source of those error code
public static class Constants
{
public static int A { get { return 1; } }
public static int B { get { return 2; } }
public static int C { get { return 3; } }
public static int x5000 { get { return 5000; } }
}
public enum EConst
{
A = 1,
B, // <= value is 2
C, // <= value is 3
x5000 = 5000,
}
They both work the same way,in my opinion enum is even more readable, why using static int?

Why does the C# compiler not complain when we use struct function inside the static methods without defining them static? [closed]

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 6 years ago.
Improve this question
Why does the compiler not complain when we use struct function inside the static methods without defining them static?
Example:
struct CustomerName{
Public String firstname, lastname;
Public String Name() => firstname + " " +lastname;
}
Public static void main(){
CustomerName MyName ;
MyName.firstname = "Kidus";
MyName.lastname = "Tekeste";
Console.WriteLine(MyName.Name());
}
This works fine in visual studio but I wonder why it worked with out it being made static. like this:
static struct CustomerName{
Public String firstname, lastname;
Public String Name() => firstname + " " +lastname;
}
If it would have been a class, would it be clearer? Same behaviour.
Firstly, struct cant be static Simple explanation
You declare and define a struct somewhere. By not defining it as static You essentially say it can be instantiated to an object of type CustomerName.
In your Main() you instantiate an object of this type and call it MyName and assign values to its fields. Works just as intended, don't you agree?

Creating data members of a class in C# [closed]

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;

Adding local variable to List [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 9 years ago.
Improve this question
public class C
{
private List<myClass> _list = new List<myClass>();
public void MyFunction()
{
myClass myClassInstance = new myClass();
// working with myClassInstance
_list.Add(myClassInstance);
}
}
Problem is that List doesn't get populated, _list.Count is always 0 :(
Well, it is depends on your desing of myClass but I see two things;
class is a keyword, that's why you should use it as a #class
Keywords are predefined, reserved identifiers that have special
meanings to the compiler. They cannot be used as identifiers in your
program unless they include # as a prefix. For example, #if is a valid
identifier but if is not because if is a keyword.
your function method missed a return type which is void looks okey for your case.
You need to rename both the instance of myClass and function to something OTHER than C# keywords. At that point you can add the value to the list
public class C
{
private List<myClass> _list = new List<myClass>();
public void MyFunction()
{
myClass myClassInstance = new myClass();
// working with myClassInstance
_list.Add(myClassInstance);
}
}

How do I get data from public interface to use? [closed]

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
}
}

Categories