C# Self Initated class - how to use in project - c#

I have created a class and self initialized it in the file - is this the best way to use it? I have another Constant class that I can use but I am unable to use this for some reason in my project, do they need to be consts?
File: test.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace DH.Models
{
public class test
{
public string testSourceCollection { get; set; }
public string testSourceKey { get; set; }
public string testSourceDatabase { get; set; }
public string testSourceCluster { get; set; }
public string testSourceTimestamp { get; set; }
public test[] testDetails = {
new test{
testSourceCollection = "SourceCollection",
testSourceDatabase = "SourceDatabase ",
testSourceKey = "SourceKey ",
testSourceTimestamp = "SourceTimestamp "
},
new ProviderRecon
{
testSourceCollection = "testSourceCollection2",
testSourceDatabase = "testSourceDatabase2",
testSourceKey = "testSourceKey2",
testSourceTimestamp = "testSourceTimestam2",
testSourceCluster = "testSourceCluster2"
}
};
}
}
I would like to use in my Worker.cs file as such
public class Worker : BackgroundService
{
var test = test.testDetails;
Console.WriteLine("2nd test: " + test.testSourceCluster )
//Prints "2nd test: testSourceCluster2"
}

You probably want testDetails to be static. You can't access (non-static) members using a type. Change public test[] testDetails = ... to public static test[] testDetails =...
However, you have a lot of non-standard namings there, which make this code confusing to read. The class test should be called Test instead. The line var test = test.testDetails; is hard to read otherwise (and probably won't compile). Same is true for your Worker class. That piece of code won't compile.

Every time when you create an instance of your class, testDetails property is initialized with new array. If you create 1000 instances for each instance testDetails is initialized with new array.
You can use static field/property to avoid create multiple instances with the same array. static keyword
Or use static readonly property/field to avoid create multiple instances with the same array. static readonly properties/fields can be initialized with static constructors. Static constructors

Related

.Net Set Class Constant to it's Namespace at compile time

Is there a nice way to set a constant to be that of a classes namespace?
namespace ACMECompany.ACMEApp.Services
{
public class MyService
{
private const string WhatWeDo = "ACMECompany.ACMEApp.Services";
private const string WouldBeNice = typeof(MyService).Namespace;
...
}
}
So that if the class if moved to another namespace we don't need to worry about these constants.
More Info
The constant is only really used for logging - where it is passed to some log method. This is all legacy code so wont be changing in the short term. I am aware of runtime ways to get this information such as This Question
We're using .NET 4 but will be upgrading soon to .NET 4.5.
You're not going to set a constant variable with a non-constant value. This is understandable, isn't it?
BTW, C# has the readonly keyword, to turn any class field to work like a constant once object construction time ends. They can or can't be static:
public class MyService
{
static MyService()
{
WouldBeNice = typeof(MyService).Namespace;
}
private static readonly string WouldBeNice;
}
or...
public class MyService
{
private static readonly string WouldBeNice = typeof(MyService).Namespace;
}
Also, you can achieve the same behavior using read-only properties:
// Prior to C# 6...
public class MyService
{
private static string WouldBeNice { get { return typeof(MyService).Namespace; } }
}
// Now using C# 6...
public class MyService
{
private static string WouldBeNice => typeof(MyService).Namespace;
}
// Also using C# 6...
public class MyService
{
// This can be even better, because this sets the namespace
// to the auto-generated backing class field created during compile-time
private static string WouldBeNice { get; } = typeof(MyService).Namespace;
}

Error when trying to keep code inside of Main method

I am trying to teach myself this so I am sure this is obvious.
I am trying to create 2 classes that I can call instances of in Program/Main. One class is a string to double tryparse method and the other will just hold variables that will be used for many things.
My problem is I can only set Main up without error if the Main Method is only holding my new instance of class statements so I am exiting code immediately.
I will post the code to the Main. Newbie code and question, any help is much appreciated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SetupMath
{
class Program
{
public static void Main(string[] args)
//Bringing in classes to inherit methods from
{
StringToDouble IntakeParse = new StringToDouble();
SetUpVar GuitAction = new SetUpVar();
}
// new instance of the StringToDouble class
// getting variable value "action" from string to double tryparse
public class StringToDouble
{
public string action { get; set; }
//converting "action" variable to "what"
public string What
{
get { return this.action; }
set { this.action = value; }
}
}
public class SetUpVar // new instance of the SetVar class
{
public string GuitAction { get; set; }
public string What { get; set; }
//Do something code
public void Work()
{
Console.WriteLine("Please enter a number", GuitAction);
What = Console.ReadLine();
Console.WriteLine("You entered: " + What);
}
}
}
}
You are writing StringToDouble and SetUpVar classes inside the Program class scope that's why they are visible only there. If you want your classes to be visible inside the whole namespace you should write them outside of Program class

How to pass parameter to class C#?

I have code as below
public class LocalDB
{
public static int e_SessionID;
public static string e_EventName;
public static string e_TimeCreate;
}
in other class:
public static LocalDB newEvent ;
public void something()
{
newEvent.e_SessionID=123;
}
but it is can not pass value.
Problem : You are trying to access the static feilds using instance reference variable newEvent as below:
newEvent.e_SessionID=123;
//^^^Here
Solution : You need to use classname to access the static fields
newEvent.e_SessionID=123;
//^^^Replace with classname LocalDB here
Replace this:
newEvent.e_SessionID = 123;
With this:
LocalDB.e_SessionID = 123;
Why don't you set them up as properties? Have a read of this SO post why prefer properties to public variables
"Fields are considered implementation details of classes and exposing them publicly breaks encapsulation."
public class LocalDB
{
public int SessionID { get; set; }
}
Static methods and variables can only invoke using the class name
and you are trying to call using the class object.
if you want to set the value of e_SessionID set the value using class name as follows
LocalDB.e_SessionID=123;
try to use property instead:
public class LocalDB
{
public int e_SessionID { get; set; }
public string e_EventName { get; set; }
public string e_TimeCreate { get; set; }
}
Prefer instance data to static data.
Static data is effectively global state. Do you have only one event in the lifetime of your program? What if you need to support multithreading? This is object-oriented programming; use objects.
Encapsulate data.
Avoid making fields public. Prefer properties, as others have stated. Note that this allows assigning the creation time at construction (and only then).
Use appropriate types.
If you are storing a date/time value, normally you would use the DateTime class.
Favor immutability.
If you know the values of properties at construction time, set them then and don't allow them to be changed.
Think about names.
Descriptive names matter, especially when you're doing maintenance after six months. I didn't change the name of LocalDB in my example, as I don't know your domain or use case. However, this class looks more like an event than a database to me. Would Event be a better name?
The following example uses C# 6 syntax; earlier versions would need to add private setters and move the initialization to the constructor.
public class LocalDB
{
public LocalDB(int sessionID, string eventName)
{
SessionID = sessionID;
EventName = eventName;
}
public int SessionID { get; }
public string EventName { get; }
public DateTime TimeCreate { get; } = DateTime.UtcNow;
}
public class Other
{
public void DoSomething()
{
NewEvent = new LocalDB(1, "Other Event");
}
public LocalDB NewEvent { get; private set; }
}
A flaw in this example is that the NewEvent property of an Other instance will be null on creation. Avoid nulls where possible. Perhaps this should be a collection of events; not knowing your use case I can't say.

How to implement a partial class with static object definition in C#

//Found the solution...
The problem was in fact that I have an array of register filled on creation (contructor method) and that array wasn't instanciated.
To make it short, I've been too noob to even put a break point in the constructor to see if .Net handled a first chance exception.
Thanks again for all the repliers. You have been really helpful. :)
Sorry again for my noobness
What have I learned today :
-You never know how .net will merge your partial class
-Be more aware of first chance exceptions
//STATE CHANGE 2012/01/30 17:00 or so
Sorry, I narrowed on the wrong problem. The problem explained here doesn't seem to be caused by the code provided therefore this question no longer needs to exist.
Thanks to the repliers!
//DEPRECATED, CLOSED ... W/E
I have a device which can be contacted by various registry such 0x01, 0x02, 0x03...
Also, I work in a development environment and the application I produce are oriented for our own environment in a small compagny.
To turn these registry into object I have chosen, a long time ago, to make a class which have it's constructor private to create it's own and only instance (As I understand, multi-ton design pattern).
Since there's a lot of registry now and the class file is getting huge I want to split it into parts : The property/function definitions and the multi-ton objects.
When I try to use this ex:
Register.cs :
namespace DeviceManagement.Register
{
public partial class Register
{
public int id { get; private set; }
public string foo { get; private set; }
public string bar { get; private set; }
protected Register(RegisterEnum id, string foo, string bar)
{
this.id = (int)id;
this.foo = foo;
this.bar = bar;
}
}
}
Register.enum.cs :
namespace DeviceManagement.Register
{
public partial class Register
{
protected enum RegisterEnum
{
reg1 = 0x01,
reg2 = 0x02 //and so on
};
}
}
Register.const.cs :
namespace DeviceManagement.Register
{
public partial class Register
{
public static readonly Register reg1 =
new Register(RegisterEnum.reg1,"foo1","bar1");
public static readonly Register reg2 =
new Register(RegisterEnum.reg2,"foo2","bar2");
//there is plenty more
}
}
I intended to use it like
namespace DeviceManagement
{
class SomeClassA
{
public void doThisOnDevice(Device device)
{
device.doSomeStuffOn(Register.Register.reg1, SomeCommonlyUsedStrategy);
}
}
}
Here's a test I did :
namespace DeviceManagement
{
class SomeClassA
{
public void testIfNull()
{
if(Register.Register.reg1 == null)
MessageBox.Show("It is null");
}
}
}
The compilator, intellisense doesn't throw any error/warning but, when I run my project, the Register objects are never instanciated. Altough, I don't have that issue when all this code is in the same class (not partial) and obviously in the same file.
I'm kind of lost, please help me.
For starters you don't need to break it out into a partial class to have it over multiple files. If you want to lump it together then you can put it in a different sub namespace in separate files, anyway ...
It looks like a namespace issue, as you need to have Register.Register.reg1 to access the static const.
EDIT
Ok, so from the feedback and re-reading the question a few more times I get the feeling that the current design probably won't quite work all in the same class definition. I think you maybe trying to force something into some thing which won't go.
So, why not try something like this:
namespace DeviceManagement.Register
{
public class Register
{
public RegisterType Type { get; private set; }
public string Foo { get; private set; }
public string Bar { get; private set; }
public Register(RegisterType type, string foo, string bar)
{
Type = type;
Foo = foo;
Bar = bar;
}
}
public enum RegisterType
{
reg1 = 0x01,
reg2 = 0x02 //and so on
}
public static class RegisterFactory
{
private static readonly Dictionary<RegisterType, Register> _dictionary = new Dictionary<RegisterType, Register>
{
{ RegisterType.reg1, new Register(RegisterType.reg1, "foo", "bar") },
{ RegisterType.reg2, new Register(RegisterType.reg2, "foo2", "bar2") }
};
public static Register GetRegister(RegisterType type)
{
return _dictionary[type];
}
}
}
And consume the register:
public class SomeClassA
{
public void DoThisOnDevice(Device device)
{
device.DoSomeStuffOn(RegisterFactory.GetRegister(RegisterType.reg1), SomeCommonlyUsedStrategy);
}
}
You could then take it a step further and load in the registry details from a configuration file which parses it on start up of your application to, you could then choose the registry type to work on from your UI etc.
Hope I've not got the wrong end of the stick.
I copy pasted your code and it works fine for me.
My advice is to use the Class View of Visual Studio. Here you can easily see if all the partial classes are defined within the same namespace and with the exactly same class name. If not, too many namespaces or classes will appear.

Global Static Class with Objects

Ok, so I know you can't have objects in a static class but i need a class that i can hold objects that are accessible from different classes. I am making a dll that will provide extended functionality to another program so i can't just inherit or pass classes around either. if need be i can just maybe make the properties of each object i need to be in the static class which would work but not be as friendly as i would like. anyone have any other ideas on how to accomplish something like this?
Actually, you can have objects in a static class -- they just have to be static objects.
For instance:
public static class SharedObjects
{
private static MyClass obj = new MyClass();
public static MyClass GetObj()
{
return obj;
}
}
And from elsewhere in your program you can call instance methods/properties/etc.:
SharedObjects.GetObj().MyInstanceMethod();
One option is to have a class with the accessors methods accessing a static object (or objects). The other parts of your system can use the class either as static or as a non-static. Here is the code:
public class GlobalInformation {
public static GlobalInformation CreateInstance() {
// Factory method through GlobalInformmation.CreateInstance()
return new GlobalInformation();
}
public GlobalInformation() {
// Regular use through new GlobalInformation()
}
static GlobalInformation() {
// Static initializer called once before class is used.
// e.g. initialize values:
_aString = "The string value";
}
public string AccessAString {
get {
return _aString;
}
}
public Foo AccessAnObject() {
return _anObject;
}
private static string _aString;
private static readonly Foo _anObject = new Foo();
}
Other parts of your system would use it as follows. Option 1:
var globalInfo = GlobalInformation.CreateInstance();
var aString = globalInfo.AssessAString;
var anObj = globalInfo.AccessAnObject();
Option 2:
var globalInfo = new GlobalInformation();
var aString = globalInfo.AssessAString;
var anObj = globalInfo.AccessAnObject();
Option 2 would be my preferred one (I'd remove the static factory method CreateInstance()) as you could change the implementation at any time including making (some of) the fields non-static. It would appear to be a regular class while sharing data.

Categories

Resources