Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can i have different type of objects in a C# *using* block?

Tags:

c#

using

using (Font font3 = new Font("Arial", 10.0f), 
           font4 = new Font("Arial", 10.0f))
{
    // Use font3 and font4.
}

I know that multiple objects of same type can be used inside a using clause.

Cant i use different types of objects inside the using clause?

Well i tried but although they were different names and different objects, they acted the same = had the same set of methods

Is there any other way to use the using class with different types?

If not, what is the most appropriate way to use it?

like image 728
Ranhiru Jude Cooray Avatar asked Jun 22 '10 10:06

Ranhiru Jude Cooray


3 Answers

using(Font f1 = new Font("Arial",10.0f))
using (Font f2 = new Font("Arial", 10.0f))
using (Stream s = new MemoryStream())
{

}

Like so?

like image 77
Jesper Palm Avatar answered Oct 24 '22 18:10

Jesper Palm


No you can't do it this way, but you can nest the using blocks.

using (Font font3 = new Font("Arial", 10.0f))
{ 
    using (Font font4 = new Font("Arial", 10.0f))
    {
        // Use font3 and font4.
    }
}

or as others said, but I'd not recommend it that way because of readability.

using(Font font3 = new Font("Arial", 10.0f))
using(Font font4 = new Font("Arial", 10.0f))
{
    // use font3 and font4
}
like image 25
this. __curious_geek Avatar answered Oct 24 '22 16:10

this. __curious_geek


You can stack using statements to accomplish this:

using(Font font3 = new Font("Arial", 10.0f))
using(Font font4 = new Font("Arial", 10.0f))
{
    // use font3 and font4
}
like image 6
Doctor Blue Avatar answered Oct 24 '22 17:10

Doctor Blue