Ashish Jain
Ashish Jain

Reputation: 82

How to determine size of the C# Object

I define my object as follows:

public class A
{
    public object Result
    {
        get
        {
            return result;
        }
        set
        {
            result = value;
        }
    }
}

and then i am storing some string value inside it as :

A.Result=stringArray;

here stringArray has 5 string values. now i want to use that object somewhere else and would like to know the length of string value inside this object. How?

Upvotes: 1

Views: 11917

Answers (3)

TyCobb
TyCobb

Reputation: 9089

If you're just looking for the length of Result if it's a string then you can do the following.

var s = Result as string;
return s == null ? 0 : s.Length;

Based on your comment while typing all this up. It sounds like the following is what you actually want

If it's array:

var array = Result as string[];
return array == null ? 0 : array.Length;

or if you want the total length of all the items in the array:

var array = Result as string[];
var totalLength = 0;
foreach(var s in array)
{
    totalLength += s.Length;
}

If you want to know the size in bytes then you need to know the encoding.

var array = Result as string[];
var totalSize = 0;
foreach(var s in array)
{
    //You'll need to know the proper encoding. By default C# strings are Unicode.
    totalSize += Encoding.ASCII.GetBytes(s).Length;
}

Upvotes: 1

Onel Sarmiento
Onel Sarmiento

Reputation: 1626

You can get the Length of the object by converting it into array of string.

For Example:

static void Main(string[] args) {

        A.Result = new string[] { "il","i","sam","sa","uo"}; //represent as stringArray

        string[] array = A.Result as string[];

        Console.WriteLine(array.Length);

        Console.Read();
}

Your object is Invalid so I rewrite:

public class A
{
    public static object Result { get; set; } //I change it to static so we can use A.Result;
}

Upvotes: 0

Vikas Gupta
Vikas Gupta

Reputation: 4465

var array  = A.Result as string[];

if (array != null)
{
    Console.WriteLine(array.Length);
}

Upvotes: 1

Related Questions