Navigation
  • Home
  • About
  • Advertise
  • Categories
  • Tags
  • Legal
  • Contact
C#
  • CSS
  • JavaScript
  • HTML5
  • HTML
  • PHP
  • Miscellaneous
  • Tools
  • WordPress
  • jQuery
  • MySQL
  • SEE ALL
Home > Categories > C#
Page 1

5 Differences Between C# and Java: Objects and Classes

C# Java Jun 21, 2012    3 comments

One of the most important aspects of C-derived languages is object orientation. Objects and classes allow programs to specify methods and variables in one portion of code and use them again wherever necessary. While the basic structures of class construction remain consistent between C# and Java, some subtle differences my cause problems for developers unaccustomed to the idiosyncrasies between the two languages.

#1: Instance-level inner classes

C#: Work-around support Instance-level inner classes Java: Support for Instance-level inner classes An inner class (also called a “nested class”) is declared entirely inside another class or interface. Although both languages support inner classes at the Class level, only Java supports these inner classes at the instance level without the need to pass around the outer object instance. Java handles the instance-level inner class with an “outer this pointer”.

#2: Partial Classes

C#: Supports partial classes Java: No support for partial classes A “partial class” is a class whose methods and variables are parceled out into multiple files. When the files are compiled, the class reassembles itself into the full class definition. While the C# 2.0 compiler (and other OOP compilers) allows for class files to merge at compile time, the Java compiler does not. In Java, each class must be in its own specific source code file.

#3: Anonymous Classes

C#: Supports statement-level anonymous classes Java: Supports implicit anonymous classes An anonymous class is just that: a class without a name. Developers often define anonymous classes within a method to build simple delegate callback objects, such as those used in listener methods. Java treats anonymous classes as implicit, but C# code must defined the anonymous class at the statement level.

#4: Properties

C#: Supports properties Java: Does not support properties A property uses the tools of a method while holding a value like a variable:

// Declare a Name property of type string: public string Name { get { return myName; } set { myName = value; } }

Although other Java-related languages and toolsets (e.g. JavaBeans and JavaScript) support similar ways of defining a property, Java does not.

#5: Events

C#: Supports events Java: Work-around support for events An event is a way that a class can notify its clients that an action has occurred that affects some method or variable within the object.  Although Java does not support the “event” keyword for this specific purpose, Java developers can create a class that has much of the same behavior as an event.

Honorable Mentions

Operator Overloading C#: Supports Java: Does not support According to the Java FAQ, Java does not support operator overloading “because C++ has proven by example that operator overloading makes code almost impossible to maintain”.

Indexers C#: Supports Java: Does not support Indexers allow class instances to be indexed and counted in ways similar to arrays for variables. Class instances in Java can still be indexed, but the “get” and “set” methods must be specified as variables.

Example: www.javacamp.org/javavscsharp/indexer.html

Conversions C#: Supports Java: Does not support C# allows both implicit and explicit conversions from one data type to another. Java requires that the user specifically state the conversion method.

...
more →
Tweet
spacer
Eric Lewis says: In my opinion, you should learn JavaScript (its actually UnityScript but thats not important) first because it is a simpler...

5 Differences Between C# and Java: Data Types

C# Java Jun 12, 2012    2 comments

The line between desktop development and web-based applications has been all but obliterated in the last few years. With the advent of smartphones, especially Google’s Java-based Android operating system, developers are scrambling to jump onto the newest technology, while fearing that the skills they have cultivated over the years may become obsolete.

Many former C++ and C# programmers are migrating their way to Java applications. While the languages are remarkably similar (as Java was built around the C and C++ structures in the 1990s), a few subtle differences can trip up even the most experienced developers.

#1: Unsigned Integers

C#: Supports 8-bit, 16-bit, 32-bit, and 64-bit unsigned integers. Java: Supports 16-bit unsigned integers only James Gosling, the creator of the Java programming language, decided against including arithmetic for unsigned integers in the initial design. In a 2001 interview with Java World magazine, he stressed that simplicity was the key to developing a robust programming language.

“One of the little experiments I tried was asking people about the rules for unsigned arithmetic in C. It turns out nobody understands how unsigned arithmetic in C works. There are a few obvious things that people understand, but many people don’t understand it.”

#2: Complex Numbers

C#: Supports complex numbers Java: No support for complex numbers Complex numbers are written in the form of “a + bi”, where “a” and “b” are integers and “i” is the square root of -1. Complex numbers are used in a wide range of applications, from electrical engineering to fluid dynamics.

#3: Value Types

C#: Supports user-defined value types Java: Supports only primitive value types C# allows users to construct their own value types. For instance, if a user wanted to construct the C# variable type SimpleVar with multiple properties, then assign values to those properties, the code would look like this:

struct SimpleVar { public int Position; public bool Exists; public double LastValue; } static void Main() { SimpleVar s; s.Position = 2; s.Exists = true; s.LastValue = 4.2; }

#4: Tuples

C#: Supports tuples Java: No support for tuples The “Tuple” class in C# consists of “a data structure that has a specific number and sequence of elements”. For instance,

var zipCodes = new Tuple<string, int, int, int, int>(“Houston”, 77006, 77098, 77002, 77019);

or

var zipCodes = Tuple.Create(“Houston”, 77006, 77098, 77002, 77019);

The Tuple class has a structure similar to the standard array, but with much less flexibility; the fields in a tuple cannot be changed or manipulated.

#5: Pointers

C#: Supports pointers Java: No support for pointers Pointer variables “point” directly to a location within the system’s memory. In a web-based language such as Java, such pointers would be useless. Instead, the Java Native Interface (JNI) handles any such functions.

As Gosling pointed out, the key advantage that Java has over C# is its simplicity. However, that simplicity requires the sacrifice of some more complex functionality, including data types.  In the next lesson, we will examine how class structures differ between these two languages.

...
more →
Tweet
spacer
MateuszBukowicz says: I suppose this was thought to be a post proving that C# is a superior languange compared to Java. Despite I believe this is true...

5 Differences Between C# and Java: Methods

C# Java May 29, 2012    5 comments

One of the biggest difference between C# and Java is how they handle methods. In both languages, methods are the building blocks of functional code: they define the variables, specify the operations carried out on those variables, and can return values to be used in other methods. Although the creators of the Java language followed many of the concepts of C-based languages, their development of methods allowed for fewer restrictions and more flexibility.

#1: Virtual Methods

C#: Methods are non-virtual by default Java: Methods are virtual by default. A virtual method allows any class that inherits that method to override its functions. In Java, all methods are virtual by default. This default setting prevents the insertion of an unrelated method with the same name in an inherited class.

In C#, the developer must specifically designate a virtual method with the “virtual” keyword:

public class Dimensions { public const double pi = Math.PI; protected double x, y; public Dimensions() { } public Dimensions (double x, double y) { this.x = x; this.y = y; } public virtual double Area() { return x*y; } }

In order to use the virtual method in an inherited class, the method must include the “override” keyword:

public class Circle: Dimensions { public Circle(double r): base(r, 0) { } public override double Area() { return pi * x * x; } }

#2: Generator Methods

C#: Supports generator methods Java: No support for generator methods Generator methods allow developers to control how a loop handles each iteration. Instead of creating an array, a generator function returns each value of the iteration as the loop processes the code. Java does not have a built-in capability to handle generator functions, and the code to create these functions in Java is often bulky and complicated. C# uses the “IEnumerable” interface to create generator functions and the “yield” command to return the values:

public class TexasCityCollection : IEnumerable<string> { public IEnumerator<string> GetEnumerator() { yield return "Houston"; yield return "Auston"; yield return "Dallas"; yield return “San Antonio”; } }

#3: Partial Methods

C#: Supports partial methods with restrictions Java: No support for partial methods Just as we saw in the previous lesson regarding partial classes, Java does not support partial methods. In C#, partial methods are allowed, but must meet certain restrictions:

·    The signatures in each part of the partial method must match. ·    The partial method must return void. ·    The partial method is “private” by default and will not accept any modifiers.

#4: Extension Methods

C#: Supports extension methods Java: No support for extension methods Extension methods allow developers to include methods to their current types without the need to create a new type or modify the existing type. The current Java language does not support extension methods, but the feature is under consideration for future versions.

#5: Conditional Methods

C#: Supports conditional methods Java: Limited support for conditional methods The C# compiler allows for conditional compiling: developers can enter parameters during compilation to determine which methods the program will use. Java also allows for conditional compiling, but this practice is typically used in the debugging process.

...
more →
Tweet
spacer
MateuszBukowicz says: I agree. I think C# is in many ways superior to Java, but not necessarily in the ways that was showed. Secondly, it looks that...

Make Legacy VB 6 Components Work With .NET Applications

C# Jan 17, 2012    2 comments

Most IT professionals do not work in state of the art design shops with all the latest developer suites available to them.

Many of us have to make older applications and components work with newer technologies.  I found myself in this predicament last year when I was required to make a new ASP.NET (3.5) web application work with a ten year old VB6.0 COM Plus Component.

When I suggested to management that I re-write the component, they said:  There’s no time. I know you can make it work. By the way, we need it by Friday. Story of a developer’s life, huh?

I got lucky.  A developer friend of mine had done just this and it turns out to be fairly simple. In order to call a VB 6.0 component or dynamic link library (.dll) from a .NET application, you need to generate a Runtime Callable Wrapper (RCW) for the older .dll using .NET’s Type Library Importer (tlbimp.exe) and reference the wrapper created by the importer in your .NET app.

The primary function of the RCW is to expose the older COM app to .NET’s Common Runtime Language (CLR).  The RCW exposes the older app to the CLR using the .NET Interfaces: INew and INewer.  These interfaces are used by the RCW to police the cache of pointers to the COM object and keep track of when they need cleaned up by the .NET garbage collection process.

Another function of the RCW is to interpret and validate types between the Unmanaged COM object and your Managed .NET application. The RCW must review method arguments and return codes and translate them into the equivalent .NET types.  Microsoft calls this reviewing process marshaling.

Next I’ll walk you through the steps to create the RCW.  In this example, my .NET Client is called MyEnterpriseWebApp and the COM object is called OldLogger.dll.

Step 1: Open a Command Window with Administrative Access.

Step 2: Change Directory (CD) to the Bin folder of the version of Visual Studio you use. This is where you will find the Type Library Importer program.  On my computer it is found here:  “c:\program files\Microsoft Visual Studio 8\SDK\v2.0\Bin\tlbimp.exe”.

Step 3: Enter the command to create the RCW as seen below.  The ‘out’ parameter is the name of your wrapper dll file.

C:\<path to tblimp.exe file>>tlbimp C:\<path to your COM Object>\COMOBJ_NAME.dll /out:C:\<path to your RCWrapper File>\WRAPPER_NAME.dll

NOTE: If you leave out the <path to your RCWrapper File>, the new wrapper file will be placed in the same folder as tlbimp.exe.

Now that the wrapper has been created let’s take a look at how to hook it up to your .NET Client application.  This wrapper can be used in any type of .NET app.

Step 1: Add a reference to your new wrapper assembly in your .NET app by right-clicking on the Project in Solution Explorer and selecting “Add Reference”.  Click the “Browse” tab and navigate to the place you put the wrapper.dll.

Step 2: Import the reference to your class.  Here is an example of importing using C#:

using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using LoggerRCW;

Step 3: In your .NET class access your COM Object as its Interface requires.  Here’s an example of how the OldLogger COM works.

namespace MyEnterpriseWebApp { public partial class _Default : System.Web.UI.Page { protected void Page_Load(Object sender, EventArgs e) { //Create Logger Object LoggerRCW.clsApplogClass oLog = new clsApplogClass(); try { //Page Load code here. } catch(Exception ex) { oLog.logMessage("Message to Log"); } finally { //Clean up Logger Object. } } } }

Viola!  Access to your old COM object from your new .NET app!

–Happy Coding

...
more →
Tweet
spacer
says: What specifically did you have trouble with? We can certainly have the author answer any questions.
Hot deals --> See all deals →
spacer LAST DAY: Verb Font Family with 18 Fonts - only $9!
spacer 10 Sleek, Responsive Bootstrap Web Templates - only $19!
spacer 17 High-Quality WordPress Themes - only $17!
spacer Responsive Slider + 3 Bonus WP Themes - only $19!

Common C# Build-Time Errors Part II: Inheritance and Interfaces

C# Jan 3, 2012    Add comment

In our last lesson, we saw many of the most basic build-time errors in C#.

In this session, we will look at some of the errors related to:

classes subclasses inheritance

Once we address some of the more common errors we will take a look at how you can fix them.

#1 Hidden Method Name Creates Overload

This conflict arises when a base class and its subclass have a function of the same name

public class MyBaseClass { public void Function() { // function code goes here } { public class MySubClass : MyBaseClass { public void Function() { // function code goes here } } public class YourClass { public void YourFunction() { SubClass ysb = new MySubClass; ysb.Function(); } }

The function YourFunction() cannot access the MyBaseClass.Function() from MySubClass because MySubClass.Function() hides it.

If the MySubClass.Function() is supposed to be hidden, the line that creates MySubClass.Function() should contain the keyword “new” to differentiate it from the MyBaseClass.Function():

public class MySubClass : MyBaseClass { new public void Function() { // function code goes here } }

If the MySubClass.Function() is supposed to be inherited polymorphically from MyBaseClass, the line that creates MySubClass.Function() should contain the keyword “override” and the MyBaseClass.Function() line should contain the keyword “virtual” to allow for the override:

public class MyBaseClass { public virtual void Function() { // function code goes here } } public class MySubClass : MyBaseClass { public override void Function() { // function code goes here } }

#2 Cannot Inherit from Sealed Class, Method or Variable

Programmers typically seal classes to protect them from modification from inherited classes, so they do not define their classes that are expected to pass methods and variables through inheritance as sealed.

public class Xray { protected virtual void Function() { Console.WriteLine("Xray.Function"); } protected virtual void Function2() { Console.WriteLine("Xray.Function2"); } } // end of class Xray public class Yankee : Xray { sealed protected override void Function()...
more →
Tweet
spacer
@DelaneySoftware tweeted: Common C# Build-Time Errors Part II: Inheritance and Interfaces @designerdepot

Common C# Build-Time Errors: Part I

C# Tools Dec 21, 2011    4 comments

Here’s the situation:

You’ve written a program in C#. You’ve checked the flowcharts, examined your coding and developed your user interface.

You’re anticipating that everything will flow as smooth as silk. You’re ready to create a build of the program and, instead of seeing a beautiful, efficient result, you get several (often incomprehensible) error message. How did this happen?

Here are SOME ways that these errors occur:

#1 Undeclared Variables

C# throws an error message on undeclared variables. This most frequently happens in one of three ways:

1) The variable is not assigned a type. The code in a “for-next loop” that reads like this:

for (nextStep = 0; nextStep < 20; nextStep++) { // loop process }

should read like this:

for (int nextStep = 0; nextStep < 20; nextStep++) { // loop process }

2) The variable name is spelled differently. Variables are case sensitive in C#, which can lead to some careless errors:

for (int nextStep = 0; nextStep < 20; nextStep++) { int workerID = nextStep; Console.WriteLine("Worker ID #:" + WorkerId); }

The compiler will view “workerID” and “WorkerId” as two different variables and view “WorkerId” as undeclared.

3) The variable is declared in a different scope. In order to use variables both inside and outside a routine (such as a “for” loop or a “while “ loop), the variable must be declared outside the routine.

for (int nextStep = 0; nextStep < 20; nextStep++) { int workerID = nextStep; } Console.WriteLine("Worker ID #:" + workerID);

This code will not display the final number in the sequence, but will throw an error due to the workerID variable’s declaration sitting inside the for loop.

#2 Variable Conversion Errors

For developers new to C#, especially those coming from more intuitive platforms such as VB.Net or ASP.Net, the lack of flexibility with variable types can be a hurdle.

Here’s an example of a variable conversion that throws a build-time error:

class MyClass { static public float TripleFloat(float t) { float fResult = 3.0 * t; return fResult; } }

Since 3.0 is a “double”-type variable, the operation will return a “double”, not a “float”, and create a build-time error. The operation needs to recast the result as a “float” to avoid the conflict:

class MyClass { static public float TripleFloat(float t) { float fResult = (float)(3.0 * t); return fResult; } }

#3 Protection Level Conflicts

Some programmers may forget that the default protection level for a class is “internal” and the default level for any member in that class is “private”.

class MyFirstClass //default protection = internal { public void NameFunction(){ MySecondClass sc = new MySecondClass(); sc.strFirstName = "Harry"; sc.strLastName = "Potter"; Console.WriteLine("Name: " + sc.strFirstName...
more →
<">
gipoco.com is neither affiliated with the authors of this page nor responsible for its contents. This is a safe-cache copy of the original web site.