Creating a new object in a class using string

Socks93

Active member
Joined
Oct 22, 2021
Messages
30
Programming Experience
Beginner
HI,

I'm working on a task where I've been asked to map data from SQL to a form. In the form the customer will fill out data for individual offices. Depending on how many offices have been entered I will then need to, iterate through each one and create a new class for each one in the following format "Office{Id}" e.g. Office123454rfd0989

Can anyone tell me the easiest way to do this?

Thanks
 
I think you need to revisit your computer programming or computer science lessons/notes. Classes are meant to represent objects that share common behaviors and attributes. Instances of a class object will distinguish themselves from other instances of the class by having varying values for those attributes (and varying behaviors if polymorphism is in play).

So for example, you do not write:
C#:
class Circle45
{
    public int Radius = 45;
}

class Circle127
{
    public int Radius = 127;
}

var c45 = new Circle45();
var c127 = new Circle127();

but rather you would write:
C#:
class Circle
{
    public int Radius { get; set; }
}

var c45 = new Circle() { Radius = 45 };
var c127 = new Circle() { Radius = 127 };
 
Creating a class for each office doesn't make sense. Classes are something that you define when you write the code, not something that get created at run time. You might define a class and create a different instance of it for each office, but it's hard to know whether that's what you're actually referring to.
 
Another idea is to use computed column if this is SQL-Server. The following uses EF Core but works with a data provider or Dapper.

Table structure:
CREATE TABLE dbo.Office
(
    Id NUMERIC(18, 0) IDENTITY(1, 1) NOT NULL,
    Computed AS CASE
            WHEN Id < 9999 THEN
                'OF' + RIGHT('000' + CONVERT(VARCHAR, Id, 10), 4)
            ELSE
                'OF' + CONVERT(VARCHAR, Id, 10)
        END PERSISTED,
    City NVARCHAR(50) NULL,
    [State] NVARCHAR(50) NULL,
    PostalCode NVARCHAR(50) NULL
    CONSTRAINT PK_Office1
        PRIMARY KEY CLUSTERED (Id ASC)
        WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON,
              ALLOW_PAGE_LOCKS = ON
             ) ON [PRIMARY]
) ON [PRIMARY];
 

Latest posts

Back
Top Bottom