vbbartlett
vbbartlett

Reputation: 179

Is it possible to cast an element directly to an Array?

Is there a way to cast a single object of T to an T[]

An example of where this would be used is in while passing a single string to a functions that requires a string[]

example

void ExistingMethod(string[] sa);
void main()
{
  string s;
  ExistingMethod(s); //<= problem is there a syntax that allows this type of cast?
}

not interested in a solution like this

string [] singleElementArray = new string[1];
singleElementArray[0] = s;
ExistingMethod(singleElementArray)

I'm looking to see if C# allows this type of casting.

I thought I saw a way that Java allows it by simply wrapping it like this ([s]) with the []. Does C# have this type of syntax?

Note, NOT interested in creating an array of 1 and assigning it...

Upvotes: 2

Views: 320

Answers (5)

Zano
Zano

Reputation: 2761

Since you state in a comment that foo() is part of a library that you can't modify, and assuming that foo() is an instance method, you could extend it to accept exactly the syntax you want.

Example original implementation of foo() in class Bar:

class Bar {
    public void foo(string[] s) {
        foreach (var s1 in s) {
            Console.WriteLine(s1);                
        }
    }
}

Your extension of foo():

static class BarExtensions {
    public static void foo(this Bar bar, string s) {
        bar.foo(new[] {s});
    }
}

Your example call, modified to use an external class:

class Program {
    static void Main() {
        var bar = new Bar();
        string s = "hello";
        bar.foo(s); // This is how you wanted to call it 
    }
}

Upvotes: 1

It&#39;sNotALie.
It&#39;sNotALie.

Reputation: 22794

Change foo(string[] sa) to foo(params string[] sa).

params lets you put an array that takes an array parameter parameter array like so : foo(foo, bar, baz); instead of foo(new[]{foo, bar, baz});

Or you could do a .Arr<T>(this T obj) function, which returns a T[]. Something like this:

public static T[] Arr<T>(this T obj)
{
return new[]{ obj };
}

and then use it like this:

foo(obj.Arr());

Upvotes: 13

JLRishe
JLRishe

Reputation: 101652

No, a single string is not an array of strings, so it wouldn't make sense to cast it to an array. The simplest thing you can do here is:

void foo(string[] sa);
void main()
{
  string s = "some value"; // A string must have a value before you can use it
  foo(new[]{ s }); 
}

Upvotes: 2

Brian Rasmussen
Brian Rasmussen

Reputation: 116401

There's no cast to allow this, but you can create an array on the fly with

string s = "blah";
foo(new [] { s });

Upvotes: 4

empi
empi

Reputation: 15881

C# has following syntax:

foo(new[] { s });

Upvotes: 2

Related Questions