Convert C# Using Statement To Java Online using CodePorting C# to Java App

Discussion in 'Programming' started by zarfishsn, Aug 6, 2012.

  1. #1
    C# use using Statement to define its scope outside of which an object or objects are disposed. But there is no equivalent syntax statement in Java. CodePorting C#2Java engine intelligently translates the C# code and handle this situation by producing try/catch block in java code. This Technique converts C# code to java code with same formatting ready to be complied.

    Following example shows migration of C# using statement in java:
    [B]C# Code:[/B]
    
    
    using System.IO;namespace CsPorter.Tests.Convert.LanguageConstructs.UsingStatement
    {
        [B]public[/B] [B]class[/B] Test2
        {
            [B]void[/B] Method()
            {
     
                [I]//some comments (vertical indent)[/I]
                using (Stream stream = [B]new[/B] FileStream("nowhere", FileMode.Open))
                {
                    stream.ReadByte();
                }
     
                    [I]//horisontal indent[/I]
                    using (Stream stream = [B]new[/B] FileStream("nowhere", FileMode.Open))
                    {
                        stream.ReadByte();
                    }
            }
        }
    } 
     
    [B]Java code generated by CodePorting:[/B]
    
    
     
    [B]package[/B] CsPorter.Tests.Convert.LanguageConstructs.UsingStatement;
     
    [I]// ********* THIS FILE IS AUTO PORTED FORM C# USING CODEPORTING.COM *********[/I]
     
    [B]import[/B] com.codeporting.csharp2java.System.IO.Stream;
    [B]import[/B] com.codeporting.csharp2java.System.IO.FileStream;
    [B]import[/B] com.codeporting.csharp2java.System.IO.FileMode;
     
    [B]public[/B] [B]class[/B] Test2
    {
        [B]private[/B] [B]void[/B] method() [B]throws[/B] Exception
        {
     
            [I]//some comments (vertical indent)[/I]
            Stream stream = [B]new[/B] FileStream("nowhere", FileMode.OPEN);
            [B]try[/B] [I]/*JAVA: was using*/[/I]
            {
                stream.readByte();
            }
            [B]finally[/B] { [B]if[/B] (stream != [B]null[/B]) stream.close(); }
     
                [I]//horisontal indent[/I]
                Stream stream1 = [B]new[/B] FileStream("nowhere", FileMode.OPEN);
                [B]try[/B] [I]/*JAVA: was using*/[/I]
                {
                    stream1.readByte();
                }
                [B]finally[/B] { [B]if[/B] (stream1 != [B]null[/B]) stream1.close(); }
        }
    }
    Code (markup):
    It is clear from above example that CodePorting C#2Java engine automatically generated the try/catch code to handle the using statement.
     
    zarfishsn, Aug 6, 2012 IP