Results 1 to 2 of 2

Thread: C# Custom Object

  1. #1

    Thread Starter
    Member
    Join Date
    Sep 2012
    Location
    Sweden
    Posts
    44

    C# Custom Object

    Hello.
    I have made a custom class with a property called BlockPos which is an integer.

    I can do this same thing with for example Width, but with my own property it doesnt work..
    Code:
    SomeShit = this.Controls[string.Format(BlockName)].BlockPos;
    Error Message:
    'System.Windows.Forms.Control' does not contain a definition for 'BlockPos' and no extension method 'BlockPos' accepting a first argument of type 'System.Windows.Forms.Control' could be found (are you missing a using directive or an assembly reference?)

    Thanks!

  2. #2
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,350

    Re: C# Custom Object

    The answer to this question is contained in the thread in the VB.NET forum that you posted to earlier. In that thread, .paul. recommended to the OP that they get the control by name from the form's Controls collection and then cast it as type Button before accessing a particular property. I replied to that saying that the cast was unnecessary because the Control.ControlCollection.Item property that was being used (in C# the indexer is the equivalent of the VB Item property) returns a Control reference and the property being accessed was a member of the Control class. I said that it's only if you need to access a member of that particular type that you need to cast as that type.

    In this case, Control has no BlockPos property so you can't access that property on a Control reference. If the actual object is some other type that inherits Control and adds a BlockPos property then you need to cast as that type in order to access that property.

    To understand casting, I like to use the following example. Let's say that you take your pet to the vet in a box. The vet knows that the box contains an animal but they don't know what kind of animal, so they don't know what treatments might be appropriate. It would be silly to bring a whole load of medicine into the treatment room that was specifically for cats without knowing that it was a cat in the box. Once you tell the vet that it is a turtle in the box, then the vet knows that anything that is OK for all animals is OK plus anything specific to turtles is also OK. In programming terms, you had an Animal reference and you just cast it as type Turtle, so now the vet can access all the members of the Turtle type.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width