Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsFree MagazinesWhite PapersSubmit Content
Discussion GroupsASP.NETWindows FormsLanguages.NET FrameworkVisual Studio.NET
Articles.NET FrameworkASP.NETToolsWindows Forms
.NET DirectoryOpen Source ProjectsUser GroupsWeb Resources
Related Topics
Visual Basic 6SQL ServerMS AccessOther DB ProductsMS Server ProductsMore Topics ...

.NET Forum / Languages / C# / January 2008

Tip: Looking for answers? Try searching our database.

[newbe] instantiating class variable in constructor

Thread view: 
Enable EMail Alerts  Start New Thread
Thread rating: 
Snaggy - 09 Jan 2008 21:06 GMT
Hi, this is my first day using c# and I must say it's cool but data
types..  I'm not use to them (php...) they're driving me crazy.

I need to declare a class variable, but I don't know it's type since
it's passed to the constructor when the object is created. I'd like
something like this:

class MyClass
   {

       public MyClass(int attribute)
       {
           if (attributes == 1)
           {
                string myDeck = "something";
           }
           else if (attributes > 1)
           {
                int myDeck = "123";
           }
       }

       public string tellMe()   // by the way I'm saying string, but
it might be integer... what the..
       {
           return myDeck;
       }
   }

how can I solve this mess? Can anyone reassure me that this compulsory
typing isn't actually just a headache?

bye!
Luca(IT)
Chris Shepherd - 09 Jan 2008 21:17 GMT
> Hi, this is my first day using c# and I must say it's cool but data
> types..  I'm not use to them (php...) they're driving me crazy.
>
> I need to declare a class variable, but I don't know it's type since
> it's passed to the constructor when the object is created. I'd like
> something like this:
[...]
> how can I solve this mess? Can anyone reassure me that this compulsory
> typing isn't actually just a headache?

Well, generally you would want to strongly type your data where possible. Is
there a practical reason you could not simply provide two separate properties to
provide access to your different data types?

Alternately, you could define your variable as "object", ie:
    private object myDeck;

Chris.
Snaggy - 09 Jan 2008 21:37 GMT
what do you mean 2 diff properties? I'd still have do declare my
variable after having constructed the object. Let me ask this, is it
possible to declare variable object wide (accessible through
this.varName) after having created the object? Or do I have to declare
them all and as object the typeToBeDefined ones?

(hope I explained myself..)

bye
sloan - 09 Jan 2008 21:42 GMT
if you don't know the type.. you can either use "object", (which is kinda
crappy)..or

Use a Generic.   Here is a sample. (see below).

As far as "compulsary typing"...strong typing makes more maintainable code.
The time spent on code is maintenance, not development.

class MyClass<T>

{

private T _model = default (T);

public MyClass(T attribute)

{

_model = attribute;

}

public T FindIt()

{

return _model;

}

}

class Program

{

static void Main(string[] args)

{

MyClass<int> mc1 = new MyClass<int>(123);

int x = mc1.FindIt();

Console.WriteLine(Convert.ToString (x));

MyClass<Exception> mc2 = new MyClass<Exception>(new Exception("You can use
any object here with Generics!"));

Exception foundEx = mc2.FindIt();

Console.WriteLine( (foundEx.Message ));

MyClass<Guid> mc3 = new MyClass<Guid>(Guid.NewGuid());

Guid g = mc3.FindIt();

Console.WriteLine(g.ToString ("N"));

}

}

> Hi, this is my first day using c# and I must say it's cool but data
> types..  I'm not use to them (php...) they're driving me crazy.
[quoted text clipped - 30 lines]
> bye!
> Luca(IT)
Snaggy - 09 Jan 2008 22:36 GMT
I'll study a bit on that.. for today I decided to change approach.
Let's make everything a Dictionary!

can you look at this code (cards' deck, with method to add card and
its attributes which might be 1 or more)

class Deck
{
   Dictionary<string, string[]> myDeck = new Dictionary<string,
string[]>();

   public string getAttribute(string name)
    {
        return myDeck[name][0];
    }
   public string getAttribute(string name, int attribute)
   {
       return myDeck[name][attribute];
   }

    public void addCard(string name, string attribute)
    {
        if (attribute.Contains(",")){
           String[] attributes = attribute.Split(',');
           myDeck.add(name, attributes);     <----  HERE
       }
       else
       {
           String[] attributes = { attribute };
           myDeck.add(name, attributes);
       }
    }

}

at the "HERE" I got this problem when tried to debug:

Error    1    'System.Collections.Generic.Dictionary<string,string[]>' does
not contain a definition for 'add' and no extension method 'add'
accepting a first argument of type
'System.Collections.Generic.Dictionary<string,string[]>' could be
found (are you missing a using directive or an assembly reference?)    C:
\Documents and Settings\Proprietario\Documenti\Visual Studio
2008\Projects\CardSke\CardSke\Program.cs    30    24    CardSke

what's that??
bye
Marc Gravell - 09 Jan 2008 23:26 GMT
> at the "HERE" I got this problem when tried to debug:
C# is case sensitive. Try Add(...)

Marc
Snaggy - 10 Jan 2008 13:14 GMT
> > at the "HERE" I got this problem when tried to debug:
>
> C# is case sensitive. Try Add(...)
>
> Marc

nope.. did it already
Jon Skeet [C# MVP] - 10 Jan 2008 13:21 GMT
<snip>

> nope.. did it already

If you've done it in both places already, it should compile. I took
your code, changed "add" to "Add" in both places, and added the
appropriate using directives, and it works fine.

Jon
Snaggy - 11 Jan 2008 16:30 GMT
> <snip>
>
[quoted text clipped - 5 lines]
>
> Jon

yeah, it seems so... it must have been some other problem too, thanks!

anyway.
Returning to the main topic.. is it possible to define a variable
that'll be class accessible in a method?
Jon Skeet [C# MVP] - 11 Jan 2008 16:31 GMT
<snip>

> Returning to the main topic.. is it possible to define a variable
> that'll be class accessible in a method?

No. You can only declare *local* variables in methods.

Jon

Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.