Monday, January 21, 2008

How To Upload Images Java

The programming language C #. Introduction to C #.

Author: José Antonio González Seco Full course available DOC and PDF formats on the author's web .
 
INTRODUCCIÓNAC #

Origin and need a new language

Features C #

Writing applications
 

clip_image002

Origin and need a new language


C # (read in English "C Sharp" and in English "C Hash") is the new general-purpose language designed by Microsoft for. NET platform. Its main artists are Scott Wiltamuth and Anders Hejlsberg, the latter also known for being the designer of the Turbo Pascal language and Delphi RAD tool. clip_image002[4] Although you can write code for the platform. NET in many other languages, C # is the only one that has been designed specifically for use in it, so to program it using C # is much easier and intuitive to do with any of the other languages \u200b\u200bas C # does not have unnecessary elements inherited. NET. For this reason, they say that C # is the native language . NET

The syntax and structure of C # is very similar to C + + or Java, since the intention n of Microsoft to facilitate migration codes written in these languages \u200b\u200bto C # and facilitate their learning to developers accustomed to them. However, its simplicity and high productivity are comparable with those of Visual Basic. A language that would have been ideal to use for these purposes is Java, but due to problems with the company that created the self-Sun-Microsoft has had to develop a new language to add to the proven virtues of Java the modifications that Microsoft was planning to add to improve it even Masy oriented language component development.


In short, C # is a programming language that takes the best features of existing languages \u200b\u200bsuch as Visual Basic, Java or C + + and combines them into one. Being relatively new does not mean it is immature, as Microsoft has written most of the BCL using it, so that your compiler is the most refined and optimized from those included in the . NET Framework SDK Continue Reading ...
 

Features C #


With the idea that more experienced programmers can get an overview of the language, following is a summarized the main features of C # Some of the features identified here are not exactly own the language but of the platform. NET in general and if it is discussed here because they have a direct impact on the language:
The code written in C # is

The size of the basic data types is fixed and independent of the compiler, operating system or machine for those compile (not as in C + +), which facilitates code portability.

    not include items of little use in languages \u200b\u200bsuch as C + + such as macros, multiple inheritance, or need a different operator from the point (
  • . ) members access spaces names (:: Currency:
      C # language incorporated the elements over the years has been proving very useful for application development and in other languages as Java or C + + is to simulate, as a basic type decimal
    • that allows high-precision operations with real 128-bit (very useful in the financial world) the inclusion of a foreach statement
  • para representar cadenas o la distinción de un tipo

bool específico para representar valores lógicos.
Orientación a objetos:
Como todo lenguaje de programación de propósito  general  actual, C# es un lenguaje orientado a objetos, aunque eso es más bien una característica del CTS que de C#. Una diferencia de este enfoque orientado a objetos respecto al de otros lenguajes como C++ es que el de C# es más puro en tanto that do not support or functions or global variables, but all code and data must be defined within the definitions of data types, which reduces problems with name conflicts and facilitates the readability of the code. C # supports all the features of the paradigm of object-oriented programming: encapsulation

, inheritance and polymorphism

.

Regarding encapsulation is important to note that apart from the typical modifiers

public, private

and protected
, C # adds a fourth internal switch called
, which can be combined with protected
and indicates that the element to the definition above Só can be accessed from the same assembly.

respect to inheritance, unlike C + + and Java-like C # only supports single inheritance of classes and that the multiple causes more headaches that facilities and the most cases their use can easily be simulated by multiple inheritance of interfaces. Anyway, This is again rather a characteristic of CTS than C #.
    other hand and unlike Java, C # was chosen to make all the methods are by default sealed and redefines are to marked with the modifier virtual
  • (as in C + +), thus avoiding errors due to accidental overrides. In addition, a side effect of this is that calls to be more efficient methods to not be default to search in the virtual function table implementation thereof which shall be called. Another side effect is that it allows calls to virtual methods can be made more efficiently to contribute to this table size is reduced.
    • component orientation: The very syntax of C # include elements of the design of components that other languages \u200b\u200bhave to be simulated by maso less complex constructions. That is, the syntax of C # allows you to define properties comfortably
    (similar to controlled access areas)
    events (controlled association response functions notifications) or
    • attributes (information about a type or its members)
    • automatically Management Memory policy: As mentioned, any language. NET has at its disposal the CLR garbage collector. This has the effect that language is not necessary to include instructions for destruction of objects. However, since the destruction of objects through the garbage collector is undetermined and it is only done when is active, whether through lack of memory, application termination explicit request in the source-, C # also provides a mechanism for liberation No deterministic resources through instruction using
    .
  • Type safety: C # include mechanisms to ensure that access to data types are always running smoothly, allowing you to prevent errors difficult to detect memory access belongs to any object and is especially necessary in a managed environment by a garbage collector. This will take measures such as: only supported conversions between compatible types . That is, between a guy and his predecessors, including types for which they have defined explicit conversion operator, and between a guy and his son type of an object of the first stores a reference the second ( downcasting ) Obviously, the latter can only see it in the CLR runtime and not the compiler, so that in fact the compiler and CLR work together to ensure correction conversions.
can not use uninitialized variables
  • . The compiler gives the fields a default consisting of them to zero and controlled by control flow analysis of source not read any local variable without being previously assigned any value.

    be seen that all access to elements of a table is made indices that are within range of it.

    can control the production overflow in arithmetic operations, informing it with an exception when it occurs. However, to achieve a better performance in arithmetic these checks are not done by default to operate but only with continuous variables (can be detected at compile time) Unlike Java, C # includes delegates , which are similar to function pointers in C + + but still an object-oriented approach, can store references to several methods simultaneously neously, and checked The methods that aim to have parameters and return value to define the type indicated. can define methods that support an indefinite number of parameters of a certain type, unlike languages \u200b\u200blike C / C + +, C # always checked that the values they spend on each call rates are appropriate.


    safe
    Instructions: To avoid common errors in C # you have imposed certain restrictions on the use of common control instructions. For example, the guard of any condition must be a conditional expression, not arithmetic, thus avoiding errors due to confusion of the equality operator (==
  • ) with the assignment (
    =
  • ) and any case of a switch must end in a break or goto
    indicating what the following conduct, which prevents accidental execution of cases and makes necessary changes.
  • unified type system: Unlike C + +, C # all data types derive always defined, even implicitly, of a common base class called System.Object
    , so you will have all the members defined in this class (ie, are "objects")
  • Unlike Java, C # this also & # 233, n applies to basic data types. In addition, to ensure that this does not impact negatively on their performance level, we have included a transparent mechanism for boxing
  • and unboxing
    • with which ensures that only treated as objects when the situation demands, and meanwhile, qualify for specific optimizations ficas. The fact that all types of language derived from a common class greatly facilitates the design of generic libraries that can store objects of any kind.
Extensibility basic types:
    C # to define, through
    • structures, data types for which apply the same optimizations as for basic data types. That is, they can be stored directly on the stack (after its creation, access will be faster destruccióny) and assigned a value and not by reference . To ensure that the latter does not have negative effects when passing structures as parameters of methods, there is the possibility of passing references to stack through the switch parameters ; meters
    ref.
    • Extensibility operators: To facilitate the readability of the code and ensuring that the new basic data types defined by the structures are the same basic level as predefined in the language, like C + + and Unlike Java, C # allows you to redefine the meaning of most operators, including conversion, both implicit and explicit conversions, as they apply to different types objects.
    operator redefinitions are made wisely, so that from a single definition of operators + +
    • and -
    the compiler can automatically deduce run on a prefix and postifja, and defining simple operators (eg +
    • ), the compiler figures out how to apply their version & # 243, n compound assignment (+ =) Also, to ensure consistency, the compiler checks that the operators always redefine opposite pairs (for example, if you redefine ==
    , we must also redefine
    ! =
    • )
    also given the opportunity, through the concept of
    indexer, to redefine the meaning
  • operator [] for data types defined by the user, which ensures that you can access it like a table. This is very useful for working with types that act as collections of objects. Extensibility switches: C # offers, through the concept of attributes , the ability to add metadata resulting from the compilation module No additional information from any source that generated by the compiler which can then be accessed at runtime through the reflection library. NET. This, rather is a characteristic of the platform. NET and not C #, can be used as a mechanism for defining new switches. Version: C # includes versioning policy for creating new versions of rates without fear that the introduction of new members cause difficult to detect errors types and children previously developed and extended to members of the same name to new introduced. If a class introduces a new method which overrides the rule should continue to call the version of his father at some point in your code difficult easily follow this rule members of the same symbol defined in child classes prior to the definition thereof in the parent class, or if you enter a new field with the same name as algú n method of a class child, the child class will stop working. To avoid this in C # we take two steps:
  • It requires that any redefinition must include the override modifier , which version of the child class would never be considered as a redefinition version of the membership in the parent class because it does not include

    override. To prevent a programmer accidentally include this switch, only allowed to include members that have the same signature as marked as redefining members by using the virtual . That also avoids the error so common in Java to be believed have redefined a member, because if the override member not exist in the parent class will be a compilation error.

  • redefinition If not considered, then it is considered that what you want is to hide the parent class method, so that the child class is as if it never existed . The compiler will warn you of this decision through a warning message can be deleted including the new switch in the definition of member in child class so explicitly indicate the intent to conceal.
Efficient:
    In principle, in C # all the code includes many restrictions to ensure their safety and not allow the use of pointers. However, unlike Java, C # is possible to bypass these restrictions by manipulating objects through pointers. It is sufficient to mark regions of code as unsafe (modifier unsafe

  • ) and these pointers can be used in a similar way to how it is done in C + +, which can be vital for situations where needed efficiency and processing speed very large.
    Compatible: to facilitate the migration of programmers, C #, not only has a syntax similar to C, C + + or Java that allows to include directly in written in C # code snippets written in these languages, but the CLR also offers, through the so-called Platform Invocation Services (PInvoke ) The ability to access native code written as non-oriented single functions such as object DLLs of the Win32 API. Note that the ability to use pointers in unsafe code permits you to easily access these functions, as they often expect to receive or return pointers. can also be accessed from code written in C # to COM objects. To facilitate this, the . NET Framework SDK includes a tool called tlbimp and
    regasm
    by which it is possible to automatically generate proxy classes that allow, respectively, using objects COM from. NET as if objects. NET objects shall be registered. NET for use from COM.
  • Finally, there is also the possibility of using ActiveX controls from code. NET and vice versa. For the first utility is used
    aximp
  • , while the latter is used for the aforementioned regasm
  • .
  • applications
    Writing
      Basic application Hello World!
    • Basically an application in C # can be viewed as a set one or more source files with instructions for the application to work as intended and are passed to the compiler to generate an executable. Each of these files is just a plain text file written using Unicode characters and following the proper syntax C #. As a first contact with the language, nothing better than a typical induction program "Hello World!" The only thing that makes run is to show on screen the message Hello World! Your code is: 1: class HelloWorld 2: {3: static void Main () 4: {5: & # 160; System.Console.WriteLine ("Hello World!") 6: & # 160;} 7:} All code written in C # was to write within a class definition, and that the l & # 237; line 1: is said to be defining a class (class ) called HolaMundo1 whose definition will be between the opening brace line 2: and its corresponding closing brace on line 7 line :
    • Within the class definition (line
    3:
) defines a method whose code name Main is the right choice among the key
    opening line 4:
      and their respective closing brace (line
    • 6: ) A method is simply a set of instructions to which are associated with a name, so enough to run later referenced by its name instead of having to rewrite them. The particle that precedes the method name indicates which type of value returned after executing the method, and in this case
    • is void
means that nothing is returned. For their part, placed in parentheses after the method name indicates what parameters it takes, and they are empty & # 237; I mean that the method does not take any. The parameters of a method can change the outcome of its execution based on values \u200b\u200bthat are given in each call.
  • The word static preceding the declaration of the return type is a modifier the meaning of the statement indicating that the method method is associated with the class within which is defined and not the objects created from it. Main () is called the entry point application, which is simply the method by which start execution. Need
static modifier to prevent
  • to call has to create an object of the class where defined. Finally, line 5: contains the instruction code to execute, that what is done is to request the implementation of m & # 233; all WriteLine ()

    class Console defined in the namespace System passing as a parameter string with the contents , Hi World! Note that text strings are sequences of characters delimited by double quotes even if those quotes are not part of the chain. For its part, a namespace may be considered for the classes is similar to what a directory is for files: a way to group them. WriteLine Method () be used very often in the coming issues, so it should be noted now that a way to call that used repeatedly is to pass an indefinite number of other parameters of any type and include in the first substring of the form {i}

    . This is done to display the console window the string passed as first parameter but replacing the substrings {i} the value converted to string torque & # 225; meters occupying the i +2 position in the call to WriteLine ()
. For example, the following 5 years I have
show the screen if x were worth 5: System.Console.WriteLine ("I have {0} YEAR I " x); To indicate how to turn every object into a string simply redefine the method ToString ()
, although this is something that will not show until the
Item 5: Classes . Before going is important to note that C # is case sensitive, which means that capitalization does not like to be written with identifiers. That is, is not the same type that it supports or CONSOLE Console, and if it is one of the two forms the compiler will fail because in the namespace System


there is no class with those names. In this regard, we note that a common mistake among Java programmers are accustomed to calling the main entry point instead of Main, which causes a runtime error while compiling the compiler does not detect & # 225; no definition of entry point.
 
entry points It has been said that the entry point an application is a method named Main that will contain the c & # 243; say where it has to start running it. So far only has been a version of
Main ()
that takes no parameters and return type is void , but in fact all possible versions are:

static void Main () static int Main () static int Main (string [] args
)
static void Main (string [] args ) As shown, there are versions of Main () that return a value of type int . A int is just a data type capable of storing integer between 1

2147 483,648 and 2,147 1 483,647, and the number returned by Main () would be interpreted as return code of the application. This value is often used to indicate whether the application successfully completed (usually value 0) or not (value as the cause of abnormal termination) and Item 8: Methods will explain how to return values. There are also versions of Main () that take a parameter to contain the list of arguments that the application was called, so it is only useful to use these versions of the entry point if the application will use These arguments for something. The type of this parameter is

string [] , which means it is a text string table (in the Item 5: Classes will explain in detail what are the tables and chains), and its name-which is to be used within the code in Main () to make reference, is args in the example, although it could gives ; rsel anyone else. Compilation command line After writing the above code with any text editor, like Notepad Windows-and stored in plain text in a file HolaMundo.cs to compile simply open a console window (MS-DOS in Windows), placed in the directory where you are and have fun as a couple & # 225; subway and compiler: csc HolaMundo.cs
 
csc.exe is the C # compiler included in the. NET Framework SDK for Microsoft Windows. Although in principle the SDK installation program automatically adds the path to seamless call from any directory if you installed via VS.NET does not occur and must be set either manually or by running the batch file Common7 \\ Tools \\ vsvars32.bat that VS.NET includes under its installation directory n, or opening the console window from the icon to Visual Studio.NET

à Command Prompt Visual Studio.NET for the group VS.NET programs in the Windows Start menu does nothing but open the console and automatically call vsvars32.bat

. In any case, if you use other compilers of C # can be varied as to make the compilation, so that what is explained here in principle only be & # 225; valid for C # compilers for Microsoft Windows. After compilation would get an executable named HolaMundo.exe whose execution produces output in the console window:
Hello World!
If the application you are going to build does not use the console window to display the output but a graphical interface screens, then it would have to compile it from the compiler option / t with the value winexe before the name of the file to compile. If not they would do so would open the console window each time you run the application window, which is usually undesirable in these applications. So, to compile a windows executable Ventanas.cs would convenient to write: csc / t: winexe Ventanas.cs

Note that although the name
 winexe  give the impression that this value for the option 
/ t
only allows to generate executables windows, in fact it is permitted to generate executables with no associated console window. Therefore also be used to generate executables that do not have any associated interface or console or graphical.
If instead of an executable, either console or windows, you want to get a library, then to compile the compiler must pass
option / t with the value
library> . For example, following the initial sample would have to write:
csc / t: library HolaMundo.cs In this case, create a file HolaMundo.dll which types of data you can & # 237, n used from other sources from the compiler a reference to them by selecting / r . For example, to compile a source executable A.cs HelloWorld class that uses the library HolaMundo.dll be written: csc / r: HolaMundo.dll A.cs Overall / r allowed to reference types defined in any assembly, so the value you provide also may be the name of an executable. In addition, each build may reference multiple assemblies including self either option / r once every one or multiple references including self in a only option / r
using commas or semicolons as separators. For example, the following three calls to the compiler are equivalent:
csc / r: HolaMundo.dll; Otro.dll; OtroMás.exe A.cs csc / R: HolaMundo.dll, Otro.dll, OtroMás.exe A.cs csc / t: HolaMundo.dll / r: Otro.dll / r: OtroMás.exe A.cs It should be noted that although not indicated anything in any compilation always default reference to the library mscorlib.dll of the BCL, which includes the types of use m & # 225; s common. If you use BCL types not included in it should be included when compiling references to libraries where they are defined (in the SDK documentation on each type of BCL can find information about where it was defined) Both executables and libraries are assembled. To generate a code module that is not part of any assembly, but contains definitions of types that may be added to assemblies that are compiled later, the value to be given the option to compile / t
is
module. For example: csc / t: module HolaMundo.cs

With the above statement would create a module called HolaMundo.netmodule could be added to compilations assembled by including as the value of the option / addmodule
. For example, to add the module before compiling the source library and bookstore Lib.cs wrote:    csc / t: library / addmodule: HolaMundo.netmodule Lib.cs  
though so far all such compilations have been made using a single source file, nothing really prevents that can be used more. For example, to compile and B.cs A.cs files in a library A.dll be implemented: csc / t: library A.cs B.cs Note that the default name given to the executable is always equal to the first source with the extension specified own the type of compilation made (. exe for executables, . dll for bookstores and . netmodule module) However, you can specify & # 160, as the option value / out any other compiler
as the following example to compile the file A.cs> as a library name Lib.exe:
  csc / t: library / out: Lib.exe A.cs    Note that although it has been given a name ending in 
. Exe the resulting file, it remains a bookstore & # 237; to and not try to run an executable and produce an error message. Obviously it makes little sense to give that extension, and only been given in this example to show that, though recommended, the file extension does not necessarily correspond really the file type of question. When specifying files to compile can also use wildcard characters Typical operating system. For example, to compile all files with extension. cs current directory in a library called Varios.dll would:
  csc / t: library / out: *. cs   varios.dll  With what needs to be careful, especially when compiling a number of sources is not compiled with both more a data type with entry point, because then the compiler does not know which one to use as the beginning of the application. To target can be specified as the value of the option 
/ main name type that contains Main () has been used as entry point. So, to compile and B.cs A.cs files into an executable which is the entry point type defined in the Principal, should write: csc / main: Main A.cs
B.cs
course, for this to work or B.cs A.cs must contain a definition of some guy named Principal with a single m & # 233; all valid as an entry point (obviously, if it contains several volveríaa have the problem of not knowing which one to use)
 Compilation Visual Studio.NET     To compile a Visual Studio.NET application must first be included within any project. To do this simply press the button New Project 
on the home page is showing only start this tool, after which he will get a screen with the look shown in Figure 1
.   In the box labeled window shown  Project Types  has to select the type of project to create. Obviously, if you go to work in C # the option should be choice will always be in the same Visual C # Projects. 
Box Templates has to select the template for the project within subtype of the type in Project Types to be done. To make a console executable, as in our case, we must select the icon labeled Console Application. If you wanted to make a library would have to select Class Library> and if Kishi make a windows executable would have to select Windows Application. Note that we make no template for modules, which is that from Visual Studio.NET can not be created.
 Finally, in the Name text box   has to write the name to give to the project and  Location  the base directory associated with it. Note that low 
Location a message informs you about which is the directory where files are stored finally the project, which will be the result of concatenating the path specified for the base directory and the name of the project.

Figure 1: Window to create new project in Visual Studio.NET
 Once set all these options, pressing OK button   Visual Studio will create the entire infrastructure to begin to work comfortably in the project. As shown in Figure 2  , this infrastructure consists of the generation of a source that will serve as a template for projects of that type ( in our case, console applications in C #): 
   Figure 2: Template for console applications generated by Visual Studio.NET   From this template, write the code for the sample application is so easy to just type 
 System.Console.WriteLine ("Hello World!" ;)   within the definition of   method Main () 
created by Visual Studio.NET. Of course, another possibility is to delete the entire workforce and replace the HelloWorld code shown above. Sea do as you do, to compile and run the application after that just press CTRL + F5 or select Debug à
 Start Without Debugging   in the main menu of Visual Studio.NET. To only compile the project, then you should select Build   à 
Rebuild All . However, in both cases, the executable is stored in the subdirectory Bin \\ Debug directory
project.
 the far right of the main window of Visual Studio.NET can find the Solution Explorer called   (if not available, select View  à  
Solution Explorer
), which is a tool that can find the necessary files that make up the project. If you select it the icon for the project you're working on and click View  à   Property Pages  get a property sheet for the project with the appearance shown in Ilustració 
n 3
:

Figure 3: Property Sheet in Visual Studio.NET project
This window allows visually configure most options that you call & # 225; the compiler command line. For example, to change the output file name (optional / out ) indicates the new name in the text box
Common Properties à General
à
Assembly Name to change the type of project to generate (option
/ t ) is used Common Properties à General
à
Output Type (as you will if you try to change it, you can not generate modules from Visual Studio.NET), and the type that contains the entry point to use (option / main ) is indicated in Common Properties à General

à Startup Object clip_image002

Finally, to add the project references to external assemblies (option

/ r

)
simply select Project à Add Reference from the main menu of VS.NET.

clip_image004 (C) 2001 José Antonio González Seco


addthis_url = ''; addthis_title = ''; addthis_pub = 'igner';

0 comments:

Post a Comment