[RESOLVED] Exposing Array parameters in User Control
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 7 of 7

Thread: [RESOLVED] Exposing Array parameters in User Control

  1. #1
    Join Date
    Feb 2003
    Location
    Ft. Worth Texas
    Posts
    30

    [RESOLVED] Exposing Array parameters in User Control

    Hi All!

    VS2010/Net 3.5

    I'm writing a user control, and I need to expose/create an array property.

    Code:
    public string[] Flavor = new string[16];
    This works within the UserControl, but how do I expose it to the program/project that's hosting the UserControl?
    For use like this:
    Code:
    MyControl.Flavor[0] = "Cherry";
    MyControl.Flavor[1] = "Grape";
    I've concidered a method using the get/set pair, but I can't figure out how to do it!

    Thanks for your help!

  2. #2
    Join Date
    Jan 2010
    Posts
    1,099

    Re: Exposing Array parameters in User Control

    Can you show us how you tried to do it?
    You should be able to simply expose the array as a string[], or in a more abstract way as IList<string>, and than simply use or change the existing array members.

    A few things you must understand - a getter will provide you with a reference to an internal array. It's a good practice not to return null, but an empty array if it contains no members. If the array is not empty, then you should be able to access or even change the elements at a given index by either mutating them (if possible, however, strings in C# are immutable), or by replacing them.

    You can do this even without a setter. What a setter would enable you is to replace the entire array itself.

    If you want to be able to dynamically change the size of the collection (by dynamically adding/removing elements), then you should use List<string> instead of an string[].

    Final note: the nature of your data (flavor kinds) strongly suggests that it is probably better not to use a collection of strings in this case, but an enumeration instead - because enums are provided as a tool for representing precisely this type of data. Of course, since you didn't provide more detailed info on what are you doing or trying to accomplish, I cannot be 100&#37; sure that's the right way to go, so you'll have to be the one to decide.

  3. #3
    Join Date
    Feb 2003
    Location
    Ft. Worth Texas
    Posts
    30

    Re: Exposing Array parameters in User Control

    Ok, Here's what I've got so far:
    Code:
    namespace ShiftPage
    {
        public partial class UserControl1 : UserControl
        {
            private string[] flavor = new string[16];  
    
            public string[] Flavor = new string[16]
            {
                get { return flavor[]; }
                set { flavor[] = value; }
            }
    
            public UserControl1()
            {
                InitializeComponent();
            }
    .....
    .....
    ...
    And obiously, the above code won't compile.

  4. #4
    Join Date
    Jan 2010
    Posts
    1,099

    Re: Exposing Array parameters in User Control

    Code:
            private string[] flavor = new string[16];  
    
            public string[] Flavor = new string[16]  // you can't initialize the array here - you did it in the previous line
            {
                get { return flavor[]; }
                set { flavor[] = value; }
            }
    Try this.

    Code:
           private string[] flavor = new string[16];  
    
            public string[] Flavor
            {
                get { return flavor[]; }
                set { flavor[] = value; }
            }
    The type of the array is string[], not string[16] - the latter is just a notation used to specify how many elements the array should be able to hold. This has nothing to do with the type. String arrays of size 3, 10, 12, or 16, or whatever are all of the same type: string[] (read "string array").

    EDIT:
    Note that you can use the setter to check if certain preconditions are met, like if the array being set has enough elements, or too many, or something else, and do something about it.
    Also, have you considered using an enum instead? Enums are rather simple, don't be afraid to check them out - for example, here.
    Last edited by TheGreatCthulhu; February 8th, 2012 at 05:47 PM.

  5. #5
    Join Date
    Feb 2003
    Location
    Ft. Worth Texas
    Posts
    30

    Re: Exposing Array parameters in User Control

    Thanks TheGreatCthulhu, for helping me with this!

    I copied your example and pasted it into my project.
    In the get part, an error on the last square bracket is: "Syntax error; value expected"
    and in the set part, flavor has an error: "...is a 'field', but used like a 'type'",
    the = sign: "Identifier expected" and value has:"cannot convert string[] to flavor[]".

    Code:
    public string[] Flavor
            {
                get { return flavor[]; }
                set { flavor[] = value; }
            }
    I have also looked into enum, but I find that I can't get it to accept variables as the items to enumerate. The "Flavor" value in the hosting program will get the "Flavor" value from an external XML file and each flavor is assigned to the host "Flavor" array. So I don't actually know what the "Flavor" value is except that it is a string. So, once I have the host "Flavor" array populated, I need to fill the UserControl "Flavor" array with the host "Flavor" array.

    I sure hope this makes sense!

  6. #6
    Join Date
    Jan 2010
    Posts
    1,099

    Re: Exposing Array parameters in User Control

    Oh, I totally missed that!
    It's simple: just delete the [] in the get & set blocks. flavor is the name of a variable, and it's used the same way as any other variable - the fact that it's an array doesn't change anything.

    So:
    Code:
    get { return flavor; }
    set { flavor = value; }
    I'll try to make things somewhat more clear. The flavor array is the backing field of the Flavor property. That is, the flavor array stores the actual data, and the Flavor property is just the way to get it from outside the class, without exposing internal implementation details. To beginners this often seems strange, as it appears that such a property doesn't do anything really useful, and that it only adds extra code in between. However, this is one of the most well known programming practices, and it has several benefits - it abstracts away implementation details, so that you can change them without affecting the rest of the program using your class; it enables you to insert various error checking or data transformation logic into the getter and/or setter; it's also a debugging aid, as it provides a centralized point for the get/set operations on the internal data, which enables you to quickly identify any such operation by simply setting a breakpoint on the property.
    So, you see, the backing field doesn't have to have a 1-to-1 mapping to a property, or the same name, and the property can have additional logic, aside from just the basic retrieve/assign functionality. The point is: the backing field is just some variable that stores data, and the property is just a way for external objects to manipulate that data.

    Same goes for arrays. The only difference is that they support the [] operator, which is just a syntactic sugar: flavor[i] is just a way for you to say "get me the i-th element of the flavor array".

    Now, there might be some confusion because the [] symbol is used in various context with slightly different meanings.
    Code:
    string[] myStringArray;   // declares a string array (string[]) variable, initialized to null.
    myStringArray = new string[10];   // initializes the array to an actual string array with 10 elements
    
    // or, in condensed form:
    string[] myStringArray = new string[10];
    
    // (Note: The array is now not null anymore, but the 
    // elements are - null is the default value for reference types.
    // Each element should be added later on in code.)
    So, here, the [] symbols are used to denote that you want an array, as opposed to just a string, and then again to inform the compiler how big the array should be.
    Note that in this case the [] is never written with the variable name (myStringArray), but always as a part of the type name.

    Other than that, when working with the whole array, and not just the elements, you would use the variable as any other:
    Code:
    myStringArray = someOtherStringArray;
    
    // or in a method which returns a string array (string[])
    public string[] MyMethod()
    {
        // do some processing...
        return myStringArray;
    }
    
    // NOTE: same goes for properties, as they are just methods in disguise...
    If you wanted to access and manipulate individual elements however, then you would use the [] operator as an indexer, on your variable.
    Code:
    myStringArray[2] = "third element";
    myStringArray[i] = i.ToString() + "-th element";
    With all that in mind, the compiler errors you got are pretty straightforward:

    > 'In the get part, an error on the last square bracket is: "Syntax error; value expected"'
    Compiler interprets "flavor[]" as a type name, but a type name cannot be used there - a variable name is expected (just "flavor").

    > 'and in the set part, flavor has an error: "...is a 'field', but used like a 'type'"',
    Along the same lines.
    The rest of the errors are related to these two, and will disappear when these are fixed.

    > 'the = sign: "Identifier expected"'
    The compiler thinks "flavor[]" is a start of a variable declaration, so it expects the variable name before the "=", but none is there.

    > 'and value has:"cannot convert string[] to flavor[]".'
    Again, the compiler thinks "flavor[]" is a type, and that you're trying to assign the value to some variable you forgot to name, and as but the type of the property is string[] and not flavor[], the compiler tells you it cannot be done.

    Hope that clears things up a bit for you.

    P.S. You also should check out this quick guide.
    Last edited by TheGreatCthulhu; February 9th, 2012 at 06:33 AM.

  7. #7
    Join Date
    Feb 2003
    Location
    Ft. Worth Texas
    Posts
    30

    Resolved Exposing Array parameters in User Control

    Thank you so much!

    Your explaination has given me an understanding that I have sought for some time. I have had other projects that I wanted to do this with, but had to devise a different approach because, although many had attempted to assist me, none were able to teach me! Thanks again!

    And, yes my problem has been solved!

Posting Permissions

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


Azure Activities Information Page

Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center