Question

Hiren Bharadwa on Wed, 12 Dec 2012 05:16:25


Hi,

I am developing one SDK.

I am getting input from the client using exposing interface from the SDK

So, I want to declares property with fixed size buffer in the interface to validate client to not insert data whose length is bigger than I specified.

Ex:

public interface IPerson
{
char[30] FirstName;
char[30] LastName;
}

Is it possible to do so.

I also want to support .NET framework 2.0 Version.

Thanks


Sponsored



Replies

Heslacher on Wed, 12 Dec 2012 06:20:01


Hi, as you have typed it here, why didn't you try it inside VS ?

Heslacher on Wed, 12 Dec 2012 06:25:09


In addition to my previous post, read the following to understand what you can declare inside an interface and what you can't : http://msdn.microsoft.com/en-US/library/87d83y5b(v=vs.100).aspx

Hiren Bharadwa on Wed, 12 Dec 2012 14:07:49


Ohh..I am realy very sorry.

I know that we can't declare fields in interface.

So, My question is how to declare property with fixed size array.

ex:

    public interface IAudio
    {
        char[30] FirstName { get; set; }

        char[30] LastName { get; set; }
    }
Note : I aim is just to validate that property don't allow morethan 30 chars. Is there any way to do it??

Heslacher on Wed, 12 Dec 2012 14:31:46


Hi,

not inside the Interface. What i would do is write in the documentation of the interface that if one will set the properties with more than the wanted ( here 30 ) characters an exception will be thrown. You need to make sure, that also the documentaion of the classes which will take the interface as parameter will respect this fact.


Hannes

If you have got questions about this, just ask.

In a perfect world,
users would never enter data in the wrong form,
files they choose to open would always exist
and code would never have bugs.

C# to VB.NET: http://www.developerfusion.com/tools/convert/csharp-to-vb/


servy42 on Wed, 12 Dec 2012 16:28:15


You can do it, you just need to provide a level of redirection.

public class NameField
{
    private char[] name = new char[30];
    public char[] Name { get { return name; } }
}

public interface IPerson
{
    NameField FirstName;
    NameField LastName;
}

That said, you should almost always be using `string` in C# instead of a character array.  Consider something like this:

public class NameField
{
    public NameField(string name)
    {
        if (name.Length > 30)
            Name = name.Substring(0, 30);
        else
            Name = name;
    }
    public string Name { get; private set; }
}

Edit, I just noticed you have .NET 2.0 as a constraint (that's unfortunate) but the only change you'll need to make is writing out the property explicitly instead of using an auto property.  I assume you can do that on your own.