Sie sind auf Seite 1von 13

What do I use in Visual Studio (C#) to perform the equivalent of Java's

System.out.println( /*stuff*/ ) ?
Try: Console.WriteLine

Console.WriteLine(stuff);
Better way is to use System.Diagnostics.Debug.WriteLine:

System.Diagnostics.Debug.WriteLine(stuff);

12
down vote
favorite

/*******************/

Does C# have the equivalent of Java's java.lang.RuntimeException?

(I.E. an exception that can be thrown without the necessity of being caught, or the
program crashing when the exception is thrown.)

SystemException is the equivalent, it is the base class of all exceptions that can be
raised by .NET code. As opposed to application exceptions.

From the comments it however sounds like you want to catch this exception. In
which case you should never use SystemException, you'll catch too many. Make
your own exception class, derived from Exception.

There are no exception specifications in .NET, in case that's what you're after.

/************/

You can index into a string in C# like an array, and you get the character at that
index.

Example:

In Java, you would say

str.charAt(8);

In C#, you would say

str[8];

/**********/

like this, which declares an array with 4 rows which each have 4 columns:
int[][] array = new int[4][4]; // JAVA

In C#, the 2nd line will not compile. In C# there are actually two kinds of arrays.
One which is basically the same as the Java array, except you can not declare the

number of columns in the same line as the number of rows. The code must be
written as follows:
int[][] array = new int[4][]; // C#
array[0] = new int[4];
array[1] = new int[4];
array[2] = new int[4];
array[3] = new int[4];

/************/
arrays.fill in java
you can simply include the method into your test class. So all required is the codepart:

public static void Fill(this Array x, object y)


{
for (int i = 0; i < x.Length; i++)
{
x.SetValue(y, i);
}
}
CSharp Equivalent of java.util.Arrays.fill using Visual Studio 2008 SP1
/***************/
string.reverse()in java

I've just had to write a string reverse function in C# 2.0 (i.e. LINQ not available) and
came up with this:

public string Reverse(string text)


{
char[] cArray = text.ToCharArray();
string reverse = String.Empty;
for (int i = cArray.Length - 1; i > -1; i--)
{
reverse += cArray[i];
}
return reverse;
}

There is a second approach that can be faster for certain string lengths which uses
Xor.

public static string ReverseXor(string s)


{
if (s == null) return null;
char[] charArray = s.ToCharArray();
int len = s.Length - 1;

for (int i = 0; i < len; i++, len--)


{
charArray[i] ^= charArray[len];
charArray[len] ^= charArray[i];
charArray[i] ^= charArray[len];
}

return new string(charArray);


}

/*******************/

Java

The following program, EnhancedForDemo, uses the enhanced for to loop through the array:
class EnhancedForDemo {
public static void main(String[] args){
int[] numbers =
{1,2,3,4,5,6,7,8,9,10};
for (int item : numbers) {
System.out.println("Count is: " + item);
}
}
}

5 down vote
favorite
I have a question to which I have not found an answer. Let's say we have in either
1
java or c# the following code:
class Car {
/* car stuff */
}

And then in Java


class Truck extends Car {
/* truck stuff */
}

and C#
class Truck : Car {
/* truck stuff again */
}

In C# the following works just fine:


List<Car> carList = new List<Car>();
//add some objects to the collection
foreach(Truck t in carList)

//do stuff with only the Truck objects in the carList


collection

This works because Truck is a subclass of Car which in simple terms means that
each Truck is also a Car. The thing is though, that type checking is done and only
Trucks are selected from carList.
If we try the same thing in Java:
List<Car> carList = new ArrayList<Car>();
//add some objects to the collection
for(Truck t : carList)
//**PROBLEM**

Because of the code inside the enhanced loop, the code will not even compile.
Instead we have to do something like this to get the same effect:
for(Car t : carList)
if(t instanceof Car)
//cast t to Truck and do truck stuff with it

It is the same idea which in C# works without any problem, but in Java you need
extra code. Even the syntax is almost the same! Is there a reason why it does not
work in Java?

/******************/
What is the equivalent of Java's final in C#?

It depends on the context.

For a final class or method, the C# equivalent is sealed.

For a final field, the C# equivalent is readonly.

For a final local variable or method parameter, there's no direct C# equivalent.

/******************/
Java Array.ToString()

Option 1
If you have an array of strings, then you can use String.Join:
string[] values = ...;

34 down vote
accepted

string concatenated = string.Join(",", values);

Option 2
If you're dealing with an array of any other type and you're using .NET 3.5 or
above, you can use LINQ:
string concatenated = string.Join(",",
values.Select(x =>
x.ToString()).ToArray());

/***************/

public static void Fill(this Array x, object y)


{
for (int i = 0; i < x.Length; i++)
{
x.SetValue(y, i);
}
}

public static string ToElementString<T>(this T[] array)


{
var builder = new StringBuilder();
builder.Append('[');
for (int i = 0; i < array.Length; i++)
{
if (i > 0)
{
builder.Append(',');
}
builder.Append(array[i]);
}
builder.Append(']');
return builder.ToString();
}

/***************/

Big integer

Native support for big integers has been introduced in .NET 4.0. Just add an
assembly reference to System.Numerics, add a using System.Numerics; declaration
at the top of your code file, and youre good to go. The type youre after is
BigInteger.

Here's using BigInteger. This method Prints Numbers in the Fibonacci Sequence up to n.
public static void FibonacciSequence(int n)
{
/** BigInteger easily holds the first 1000 numbers in the Fibonacci
Sequence. **/
List<BigInteger> fibonacci = new List<BigInteger>();
fibonacci.Add(0);
fibonacci.Add(1);
BigInteger i = 2;
while(i < n)
{
int first = (int)i - 2;
int second = (int) i - 1;

BigInteger firstNumber = fibonacci[first];


BigInteger secondNumber = fibonacci[second];
BigInteger sum = firstNumber + secondNumber;
fibonacci.Add(sum);
i++;

foreach (BigInteger f in fibonacci) { Console.WriteLine(f); }


}
public static BigInteger valueOf( long val )

Description
Returns a BigInteger with the specified value. This factory is provided in preference to a
(long) constructor because it allows for reuse of frequently used BigIntegers (like 0 and 1),
obviating the need for exported constants.

Java Map equivalent in C#

116 down
vote
I'm trying to hold a list of items in a collection with a key of my choice. In Java, I
favorite
would simply use Map as follows:
8
class Test {
Map<Integer,String> entities;

public String getEntity(Integer code) {


return this.entities.get(code);
}

Is there an equivalent way of doing this in C#?


System.Collections.Generic.Hashset doesn't uses hash and I cannot define a
custom type key System.Collections.Hashtable isn't a generic class
System.Collections.Generic.Dictionary doesn't have a get(Key) method
You can index Dictionary, you didn't need 'get'.
Dictionary<string,string> example = new Dictionary<string,string>();
...
example.Add("hello","world");
...
Console.Writeline(example["hello"]);

An efficient way to test/get values is TryGetValue (thanx to Earwicker):


if (otherExample.TryGetValue("key", out value))
{
otherExample["key"] = value + 1;
}

With this method you can fast and exception-less get values (if present).
218 down
vote
Dictionary is probably the closest. System.Collections.Generic.Dictionary
accepted implements the System.Collections.Generic.IDictionary interface (which is
similar to Java's Map interface).
Some notable differences that you should be aware of:

Adding/Getting items
o Java's HashMap has the put and get methods for setting/getting items

myMap.put(key, value)

MyObject value = myMap.get(key)

o C#'s Dictionary uses the Item property for setting/getting items

myDictionary.Item[key] = value

null

MyObject value = myDictionary.Item[key]

keys

o Java's HashMap allows null keys


o .NET's Dictionary throws an ArgumentNullException if you try to
add a null key

Adding a duplicate key


o Java's HashMap will replace the existing value with the new one.
o .NET's Dictionary will replace the existing value with the new one if
you use the Item property. If you use the Add method, it will instead
throw an ArgumentException.

Attempting to get a non-existent key


o Java's HashMap will return null.
o .NET's Dictionary will throw a KeyNotFoundException. You can
use the TryGetValue method instead of the Item property to avoid
this:
MyObject value = null; if (!
myDictionary.TryGetValue(key, value)) { /* key doesn't
exist */ }

Dictionary's

has a ContainsKey method that can help deal with the previous two

problems.
First of all, C# Dictionary is a normal class, which means that you can create an instance out of it
directly while Java Map is an interface, which requires one of the three implementing classes,
HashMap, LInkedHashMap, and TreeMap to instantiate it.
Second, C# Dictionary allows you to change the value of an entry by using indexer directly
while Java Map requires you to get the value first, change it, and then put it back.
Third, C# Dictionary does not allow entries with the same key to be added whereas Java Map
allows you to do so. Under the hood, Java Map overwrites the old value with the new value of
the same key. So both C# Dictionary and java Map end up with one entry per key.
The following sample code illustrates these differences.

C#
Dictionary<string, string> d = new Dictionary<string, string>();
d.Add("A", "AA");
Console.WriteLine(d["A"]); // result: "AA"

// d.Add("A", "BB");
// The above is not allowed: Trigger runtime Exception
// The key "A" has been added already.

d["A"] = "BB";
Console.WriteLine(m["A"]); // result: "BB"
=========================
Java
Map<String, String> m = new LinkedHashMap<String, String>();
m.put("A", "AA");
System.out.println(m.get("A"));

// result: "AA"

// m.get("A") = "BB";
// The above is not allowed: Trigger compilation Exception.
// The left-hand side of an assignment must be a variable

m.put("A", "BB"); // re-putting is OK in Java but not in C#


System.out.println(m.get("A"));
// result: "BB"

/*************/
C# - Print dictionary
private void button1_Click(object sender, EventArgs e)
{
Dictionary<DateTime, string> dictionary = new Dictionary<DateTime,
string>();
dictionary.Add(monthCalendar1.SelectionStart, textBox1.Text);
foreach (KeyValuePair<DateTime, string> kvp in dictionary)
{
//textBox3.Text += ("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
}
}

In Java, what type represents a function or lambda expression that takes 3


parameters?

Java 8 has Supplier<T> for 0 parameter functions, Function<T, R> for 1


parameter functions, and BiFunction<T, U, R> for 2 parameter functions.

up vote 4
down vote
favorite
1

What type represents a function or lambda expression that takes 3 parameters


like in
SomeType lambda = (int x, double y, String z) -> x; // what is
SomeType?
In C#, Func<T, TResult> is overloaded for up to 16 parameters so we could

write
Func<int, double, string, int> lambda = (int x, double y, string
z) => x;

Does the Java standard libraries provide anything similar or do you have to
write your own "TriFunction" interface to handle functions with 3 arguments?

checked (C# Reference)


accept Edit
ed

Eric Lippert has a two-part blog post "What is the unchecked keyword good for?": Part
1 -- Part 2

"Checked" is a block keyword that enables arithmetic overflow checking. Normally, if


an integer operation exceeds the maximum or minimum value that the type can handle,
the operation proceeds anyway, and the result just cycles like an odometer. So, for
example:
byte b = byte.MaxValue;
Console.WriteLine(b);
// 255 (11111111)
Console.WriteLine(++b);
// 0
(00000000)
Placing this snippet in a checked block prevents the overflow, and

throws an OverflowException:
checked
{
byte b = byte.MaxValue;
Console.WriteLine(b);
try
{

// b=255

instead the runtime

Console.WriteLine(++b);
}
catch (OverflowException e)
{
Console.WriteLine(e.Message);
resulted in an overflow."
}

// "Arithmetic operation
// b = 255

What is the equivalent of the Java BigDecimal class in C#?

C# only has BigInteger built it (in .NET framework 4).


Is decimal enough precision for your task? It's a 128-bit number that can hold values in the
range 1.0 1028 to 7.9 1028.

Das könnte Ihnen auch gefallen